How to reverse list python
How to reverse list python
How to Reverse a List in Python
By Dan Bader — Get free updates of new posts here.
A step-by-step tutorial on the three main ways to reverse a Python list or array: in-place reversal, list slicing, and reverse iteration.
Reversing a list is a common operation in Python programming.
For example, imagine you had a sorted list of customer names that your program displays in alphabetical (A-Z) order. Some of your users would like to view the customer list so that the names are in reverse alphabetical order. How are you going to flip the order of this existing list on its head? Or in other words:
What’s the best way to reverse the order of a list in Python?
In this article you’ll see three different ways to achieve this result in “plain vanilla” Python, meaning without the use of any third-party libraries:
All examples I’m using here will be based on the following list object containing the numbers 1 through 5:
Ready? Let’s reverse some lists together!
Option #1: Reversing a List In-Place With the list.reverse() Method
Every list in Python has a built-in reverse() method you can call to reverse the contents of the list object in-place. Reversing the list in-place means won’t create a new list and copy the existing elements to it in reverse order. Instead, it directly modifies the original list object.
Here’s an example:
The reverse() method modifies the sequence in place for economy of space when reversing a large sequence. To remind users that it operates by side effect, it does not return the reversed sequence. (Source: Python 3 Docs)
In-place reversal has some benefits and some downsides. On the plus side, it’s a fast operation—shuffling the list elements around doesn’t require much extra memory, as we’re not creating a full copy of the list.
However, reversing a list in-place overwrites the original sort order. This could be a potential downside. (Of course, to restore the original order you coud simply reverse the same list again.)
From a code readability standpoint, I like this approach. The syntax is clear and easy to understand, even for developers new to Python or someone who comes from another language background.
Option #2: Using the “ [::-1] ” Slicing Trick to Reverse a Python List
Python’s list objects have an interesting feature called slicing. You can view it as an extension of the square-brackets indexing syntax. It includes a special case where slicing a list with “ [::-1] ” produces a reversed copy:
Reversing a list this way takes up a more memory compared to an in-place reversal because it creates a (shallow) copy of the list. And creating the copy requires allocating enough space to hold all of the existing elements.
Note that this only creates a “shallow” copy where the container is duplicated, but not the individual list elements. Instead of duplicating the list elements themselves, references to the original elements are reused in the new copy of the container. If the elements are mutable, modifying an element in the original list will also be reflected in the copy.
The biggest downside to reversing a list with the slicing syntax is that it uses a more advanced Python feature that some people would say is “arcane.” I don’t blame them—list slicing is fast, but also a little difficult to understand the first time you encounter its quirky syntax.
When I’m reading Python code that makes use of list slicing I often have to slow down and concentrate to “mentally parse” the statement, to make sure I understand what’s going on. My biggest gripe here is that the “ [::-1] ” slicing syntax does not communicate clearly enough that it creates a reversed copy of the original list.
Using Python’s slicing feature to reverse a list is a decent solution, but it can be a difficult to read to the uninitiated. Be sure to remember the wise words of master Yoda: With great power, great responsibility comes 🙂
Sidebar: How does list slicing work in Python?
Reversing a list this way takes advantage of Python’s “slicing” syntax that can be used to do a number of interesting things. List slicing uses the “ [] ” indexing syntax with the following “ [start:stop:step] ” pattern:
Adding the “ [1:3] ” index tells Python to give us a slice of the list from index 1 to index 2. To avoid off-by-one errors it’s important to remember that the upper bound is exclusive—this is why we only got [2, 3] as the sub-list from the [1:3] slice.
All of the indexes are optional, by the way. You can leave them out and, for example, create a full (shallow) copy of a list like this:
The step parameter, sometimes called the stride, is also interesting. Here’s how you can create a copy of a list that only includes every other element of the original:
Earlier we used the same “step” trick to reverse a list using slicing:
Option #3: Creating a Reverse Iterator With the reversed() Built-In Function
Reversing a list using reverse iteration with the reversed() built-in is another option. It neither reverses a list in-place, nor does it create a full copy. Instead we get a reverse iterator we can use to cycle through the elements of the list in reverse order:
Using reversed() does not modify the original list. In fact all we get is a “view” into the existing list that we can use to look at all the elements in reverse order. This is a powerful technique that takes advantage of Python’s iterator protocol.
So far, all we did was iterating over the elements of a list in reverse order. But how can you create a reversed copy of a list using Python’s reversed() function?
Notice how I’m calling the list() constructor on the result of the reversed() function?
Using the list constructor built-in keeps iterating until the (reverse) iterator is exhausted, and puts all the elements fetched from the iterator into a new list object. And this gives us the desired result: A reversed shallow copy of the original list.
I really like this reverse iterator approach for reversing lists in Python. It communicates clearly what is going on, and even someone new to the language would intuitively understand we’re creating a reversed copy of the list. And while understanding how iterators work at a deeper level is helpful, it’s not absolutely necessary to use this technique.
Summary: Reversing Lists in Python
List reversal is a fairly common operation in programming. In this tutorial we covered three different approaches for reversing a list or array in Python. Let’s do a quick recap on each of those approaches before I’ll give you my final verdict on which option I recommend the most:
Option 1: list.reverse()
Python lists can be reversed in-place with the list.reverse() method. This is a great option to reverse the order of a list (or any mutable sequence) in Python. It modifies the original container in-place which means no additional memory is required. However the downside is, of course, that the original list is modified.
Option 2: List Slicing Trick
You can use Python’s list slicing syntax to create a reversed copy of a list. This works well, however it is slightly arcane and therefore not very Pythonic, in my opinion.
Option 3: reversed()
Python’s built-in reversed() function allows you to create a reverse iterator for an existing list or sequence object. This is a flexible and clean solution that relies on some advanced Python features—but it remains readable due to the clear naming of the reversed() function.
If you’re wondering what the “best” way is to reverse a list in Python my answer will be: “It depends.” Personally, I like the first and third approach:
The list.reverse() method is fast, clear and speaks for itself. Whenever you have a situation where you want to reverse a list in-place and don’t want a copy and it’s okay to modify the original, then I would go with this option.
If that isn’t possible, I would lean towards the reversed iterator approach where you call reversed() on the list object and you either cycle through the elements one by one, or you call the list() function to create a reversed copy. I like this solution because it’s fast and clearly states its intent.
I don’t like the list slicing trick as much. It feels “arcane” and it can be difficult to see at a glance what’s going on. I try to avoid using it for this reason.
Note that there are other approaches like implementing list reversal from scratch or reversing a list using a recursive algorithm that are common interview questions, but not very good solutions for Python programming in the “real world.” That’s why I didn’t cover them in this tutorial.
If you’d like to dig deeper into the subject, be sure to watch my YouTube tutorial on list reversal in Python. It’s also embedded at the top of the article. Happy Pythoning!
Python: Reverse a List (6 Easy Ways)
While learning six different methods to reverse a list in Python may seem excessive, one of the beautiful things about Python is the flexibility it affords. Some methods will fit better into your style, while others may be more performant or easier to read.
Let’s get started!
Table of Contents
How does list indexing work in Python?
One of the attributes of Python lists is that they are ordered and indexed. This means that we can access (and modify) a list based on its index.
In the next section, you’ll learn how to use the Python reversed() function to reverse a list in Python.
Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.
Reverse a Python List Using the reversed function
Let’s take a look at how we can use this method to reverse a Python list:
Because of this, we need to use the list() function to create a list out of the iterator object. Similarly, we could instantiate a separate list and iterate over the iterator object, as you’ll learn later in the tutorial.
Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings!
Reverse a Python List Using the reverse method
The method works in-place, meaning there is no need to re-assign the list. If you do want to assign the old list to a new list, you’ll need to first create a copy of the original list.
If we did want to assign the reversed list to a new variable while keeping the original, we will need to write a bit more code. Let’s take a look at how this works:
In the next section, you’ll learn how to reverse a list by using list indexing.
Need to check if a key exists in a Python dictionary? Check out this tutorial, which teaches you five different ways of seeing if a key exists in a Python dictionary, including how to return a default value.
Reverse a Python List Using List Indexing
When indexing a list, people generally think of accessing all items between a start and an end position. However, you can also include a step variable that allows you to move across indices at different rates.
Moving over a list from end to beginning is the same as reversing it. Let’s see how we can use Python’s list indexing to reverse a list:
We return a new list here by iterating over each item in a reverse order, thereby reversing our list.
Need to check if a key exists in a Python dictionary? Check out this tutorial, which teaches you five different ways of seeing if a key exists in a Python dictionary, including how to return a default value.
Reverse a Python List Using the Slice Method
Python also provides a slice() function that allows us to index an object in the same way that the list indexing method works above. The function creates a slice object that allows us to easily reuse a slice across multiple objects. Because of this, we could apply the same indexing across different lists.
Let’s see how we can use the function in Python:
The benefit of this approach is that we can assign a custom slice that can be easily re-used, without needing to modify multiple items.
In the next section, you’ll learn how to use a for loop to return a list in the opposite order.
Reverse a Python List Using a For Loop
Python for loops are great ways to repeat an action for a defined number of times. We can use the reversed() and iterate over its items to create a list in the reverse order.
Let’s see how this can be done:
This method is actually very similar to what we do with the reversed() function method above. However, if the result of the function isn’t clear to readers, this result may actually be easier to follow.
In the final section of this tutorial, you’ll learn how to use a list comprehension to return a Python list in the opposite order.
Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.
Reverse a Python List Using a List Comprehension
Similar to how we can use a for loop for this, we can also use a list comprehension. Rather than simply converting the for loop to a list comprehension, however, we’ll use a slightly different approach to accomplish our goal.
We will iterate over each item in our original list in the negative order. Let’s take a look at what this looks like:
In this list comprehension, we access each index from the last to the first, decreasing by 1. We start out range using the max index (which is equal to the length of the original list, minus 1).
Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.
Conclusion
In this tutorial, you learned how to reverse a list in Python. You learned how list indexing works and how this can be used to reverse a list. You also learned how to use the reverse() and reversed() methods, as well as for loops and list comprehensions.
To learn more about lists in Python, check out the official documentation here.
How to Reverse a List in Python
In this Python tutorial, we will learn how to reverse a list in python. And we will cover different examples related to reversing a list. Here is the list of examples that we are going to cover.
Reverse a list in python with reverse function
Python has an in-built function called reverse() that we can use to reverse a Python list. Let us see an example. We will create a list and reverse it using the reverse() function. have a look at the code below.
In this way, you can use the in-built reverse() function to reverse a list.
Reverse a list in python with reversed iterator
There is another in-built option to reverse a list in python. We can use the reversed iterator. Using this option, we can iterate our list in reverse order or we can also store the results in the form of a list. Let us see how.
You can see that the elements are printed in reverse order.
Similarly, you can use this reversed iterator to make a list. But you have to convert this iterator object into a list.
In this way, you can use the reversed iterator to get a reversed list in python.
Reverse a list in python without reverse function
When we want to reverse a list in python, we generally use the reverse() function. But we can also write our own logic to complete the same task.
In the below sections, I have explained some of the methods that you can use to reverse a list in python without the reverse() function.
How to reverse a list in python using while loop
You can use the while loop to reverse a list in python. Look at the code below:
In this way, you can use the while loop to reverse a list in python.
Reverse a list in python using for loop
You can also use the for loop to reverse a list in python. I will explain various examples where I will use the for loop to reverse a list.
Example 1:
Consider the following python code:
Now let us see another example of reversing a list using the for loop.
Example 2:
In this example, we will use the insert() function along with the pop() method of the list to reverse a list. The pop() method deletes the last element of the list and returns this deleted value that we can store into a variable.
This time we will not create a new list and reverse the elements in the existing list only.
Thus, you might have learned how you can use the pop() and the insert() function with for loop to reverse a list.
Example 3:
In this example, I will explain a very efficient way of reversing a list without the use of the inbuilt functions. Look at the code below;
Explanation of code:
Original List: [32, 65, 79, 45, 35, 62, 74]
Length of list: 7
Number of iterations: int(7/2) = 3
Iteration 1:
[74, 65, 79, 45, 35, 62, 32]
Iteration 2:
[74, 62, 79, 45, 35, 65, 32]
Iteration 3:
[74, 62, 35, 45, 79, 65, 32]
You can see that in the last iteration, we got our list reversed. In this way, you can use the for loop to reverse a list in python in a very efficient way.
Example 4:
The below example is just for practice and is not a feasible solution because of its high space and time complexity.
In this method, we are iterating over the original list elements. We are converting each element into a list and concatenating this with the new list which is initially empty.
Reverse a list in python using slicing
In this section, you will learn how you can use the slicing method to reverse a list. In this method, we have to make a new copy of the list. This increases the space requirements of a program.
Have a look at the code below:
You can see that a copy of the list is storing the elements in reverse order. In this way, you can use the slicing or indexing method to get a list in reversed order.
Reverse a list in python using recursion
You can also use some recursion methods to reverse a list in python. Let us understand with the help of an example.
Let me explain this visually:
Original List: rev([43, 56, 23, 75, 92, 34, 45])
Iteration 1:
Now this function will break into:
[45] + rev([43, 56, 23, 75, 92, 34])
Iteration 2:
Similarly, the function will again break into:
[45] + [34] + rev([43, 56, 23, 75, 92])
Iteration 3:
[45] + [34] + [92] + rev([43, 56, 23, 75])
Iteration 4:
[45] + [34] + [92] + [75] + rev([43, 56, 23])
Iteration 5:
[45] + [34] + [92] + [75] + [23] + rev([43, 56])
Iteration 6:
[45] + [34] + [92] + [75] + [23] + [56] + rev([43])
which is equivalent to:
[45] + [34] + [92] + [75] + [23] + [56] + [43] = [45, 34, 92, 75, 23, 56, 43]
Hence at the last iteration, we got our list reversed. In this way, you can use the recursion method to reverse a list in python.
You may also like to read the following python tutorials.
Thus, you might have learned the various methods to reverse a list in python. the following is the list of methods that we discussed above.
Entrepreneur, Founder, Author, Blogger, Trainer, and more. Check out my profile.
Python reverse list [duplicate]
I’m trying to reverse a string and using the below code but the resultant reverse list value is None.
8 Answers 8
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
This is my personal favorite way to reverse a string:
or, if you want to reverse the word order:
Use this instead:
Also note that the method you have provided only reverses the words, not the text. @ron.rothman provided a link that does detail how to reverse a string in its entirety.
Various reversals on a string:
For future reference when an object has a method like [].reverse() it generally performs that action o n the object (ie. the list is sorted and returns nothing, None) in contrast to built in functions like sorted which perform an action on an object and returns a value (ie the sorted list)
The for loop iterates the string from end (last letter) to start (first letter)
Based on comments and other answers:
Method chaining does work in Python after all.
List reverse can be done using more than one way.
As mentioned in previous answers two are very prominent, one with reverse() function and two with slicing feature. I’m giving some insights on which one we should prefer. We should always use reverse() function for reversal of a Python list. Two reasons, one in-place reversal and two faster than other. I’ve some figures to support my answer,
For 1000 integer list, reverse() function performed better compared to slicing.
Not the answer you’re looking for? Browse other questions tagged python or ask your own question.
Linked
Related
Hot Network Questions
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Table of Contents
Are you diving deeper into Python lists and wanting to learn about different ways to reverse them? If so, then this tutorial is for you. Here, you’ll learn about a few Python tools and techniques that are handy when it comes to reversing lists or manipulating them in reverse order. This knowledge will complement and improve your list-related skills and make you more proficient with them.
In this tutorial, you’ll learn how to:
To get the most out of this tutorial, it would be helpful to know the basics of iterables, for loops, lists, list comprehensions, generator expressions, and recursion.
Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.
Reversing Python Lists
Sometimes you need to process Python lists starting from the last element down to the first—in other words, in reverse order. In general, there are two main challenges related to working with lists in reverse:
Reversing Lists in Place
Note: Most of the examples in this tutorial use a list of numbers as input. However, the same tools and techniques apply to lists of any type of Python objects, such as lists of strings.
Okay! That was quick and straightforward! Now, how can you reverse a list in place by hand? A common technique is to loop through the first half of it while swapping each element with its mirror counterpart on the second half of the list.
Python provides zero-based positive indices to walk sequences from left to right. It also allows you to navigate sequences from right to left using negative indices:
Here’s a representation of the whole process:
Creating Reversed Lists
An important point to note when you’re using reversed() is that it doesn’t create a copy of the input list, so changes on it affect the resulting iterator:
Another important point to highlight is that you can’t use reversed() with arbitrary iterators:
Another point to note is that you can’t use reversed() with unordered iterables:
Reversing Lists Through Slicing
Note: You can omit the second colon ( : ) in a slicing operator when the default value ( 1 ) meets your current needs.
If you fully rely on implicit offsets, then the slicing syntax gets shorter, cleaner, and less error-prone:
Here’s how you can use slice() to create a reversed copy of an existing list:
Generating Reversed Lists by Hand
So far, you’ve seen a few tools and techniques to either reverse lists in place or create reversed copies of existing lists. Most of the time, these tools and techniques are the way to go when it comes to reversing lists in Python. However, if you ever need to reverse lists by hand, then it’d be beneficial for you to understand the logic behind the process.
In this section, you’ll learn how to reverse Python lists using loops, recursion, and comprehensions. The idea is to get a list and create a copy of it in reverse order.
Using a Loop
The first technique you’ll use to reverse a list involves a for loop and a list concatenation using the plus symbol ( + ):
Note: The example above uses a wasteful technique because it creates several lists only to throw them away in the next iteration.
Using Recursion
You can also use recursion to reverse your lists. Recursion is when you define a function that calls itself. This creates a loop that can become infinite if you don’t provide a base case that produces a result without calling the function again.
You need the base case to end the recursive loop. When it comes to reversing lists, the base case would be reached when the recursive calls get to the end of the input list. You also need to define the recursive case, which reduces all successive cases toward the base case and, therefore, to the loop’s end.
Here’s how you can define a recursive function to return a reversed copy of a given list:
Note: In the recursive case, you can replace a_list[:1] with [a_list[0]] to get a similar result.
The commented call to print() at the beginning of the else clause is just a trick intended to show how subsequent calls reduce the input list toward the base case. Go ahead and uncomment the line to see what happens!
Using a List Comprehension
If you’re working with lists in Python, then you probably want to consider using a list comprehension. This tool is quite popular in the Python space because it represents the Pythonic way to process lists.
Here’s an example of how to use a list comprehension to create a reversed list:
Iterating Through Lists in Reverse
Up to this point, you’ve learned how to create reversed lists and also how to reverse existing lists in place, either by using tools specially designed to accomplish that task or by using your own hand-coded solutions.
In day-to-day programming, you might find that iterating through existing lists and sequences in reverse order, typically known as reverse iteration, is a fairly common requirement. If that’s your case, then you have several options. Depending on your specific needs, you can use:
In the following few sections, you’ll learn about all these options and how they can help you iterate over lists in reverse order.
The Built-in reversed() Function
Here’s how you can use reversed() to iterate through the items in a list in reverse order:
The first thing to note in this example is that the for loop is highly readable. The name of reversed() clearly expresses its intent, with the subtle detail of communicating that the function doesn’t produce any side effects. In other words, it doesn’t modify the input list.
The loop is also efficient in terms of memory usage because reversed() returns an iterator that yields items on demand without storing them all in memory at the same time. Again, a subtle detail to note is that if the input list changes during the iteration, then the iterator sees the changes.
The Slicing Operator, [::-1]
The second approach to reverse iteration is to use the extended slicing syntax you saw before. This syntax does nothing in favor of memory efficiency, beauty, or clarity. Still, it provides a quick way to iterate over a reversed copy of an existing list without the risk of being affected by changes in the original list.
Here’s how you can use [::-1] to iterate through a copy of an existing list in reverse order:
Note: Compared to extended slicing, reversed() is way more readable, runs faster, and uses substantially less memory. However, it’s affected by changes in the input list.
You can take advantage of this kind of slicing to safely modify the original list while you iterate over its old items in reverse order. For example, say you need to iterate over a list of numbers in reverse order and replace every number with its square value. In this case, you can do something like this:
Reversing Python Lists: A Summary
Up to this point, you’ve learned a lot about reversing lists using different tools and techniques. Here’s a table that summarizes the more important points you’ve already covered:
Feature | .reverse() | reversed() | [::-1] | Loop | List Comp | Recursion |
---|---|---|---|---|---|---|
Modifies the list in place | ✔ | ❌ | ❌ | ✔/❌ | ❌ | ❌ |
Creates a copy of the list | ❌ | ❌ | ✔ | ✔/❌ | ✔ | ✔ |
Is fast | ✔ | ✔ | ❌ | ❌ | ✔ | ❌ |
Is universal | ❌ | ✔ | ✔ | ✔ | ✔ | ✔ |
A quick look at this summary will allow you to decide which tool or technique to use when you’re reversing lists in place, creating reversed copies of existing lists, or iterating over your lists in reverse order.
Sorting Python Lists in Reverse Order
Now your list is fully sorted and also in reverse order. This is quite convenient when you’re working with some data and you need to sort it and reverse it at the same time.
The reverse argument to sorted() allows you to sort iterables in descending order instead of in ascending order. So, if you need to create sorted lists in reverse order, then sorted() is for you.
Conclusion
Reversing and working with lists in reverse order might be a fairly common task in your day-to-day work as a Python coder. In this tutorial, you took advantage of a couple of Python tools and techniques to reverse your lists and manage them in reverse order.
In this tutorial, you learned how to:
All of this knowledge helps you improve your list-related skills. It provides you with the required tools to be more proficient when you’re working with Python lists.
Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.
About Leodanis Pozo Ramos
Leodanis is an industrial engineer who loves Python and software development. He’s a self-taught Python developer with 6+ years of experience. He’s an avid technical writer with a growing number of articles published on Real Python and other sites.
Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:
Master Real-World Python Skills With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
Master Real-World Python Skills
With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
What Do You Think?
What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.
Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!
Related Tutorial Categories: basics python