- Python Reverse List with Slicing — An Illustrated Guide
- Slicing with Default Start and Stop Values
- Alternatives Reversing List
- Where to Go From Here?
- How to Reverse Python Lists | In-place, slicing & reversed()
- 1. Reversing lists in-place using reverse()
- 2. Reversing lists using slicing (creates a new copy)
- 3. Reversing lists using reversed
- Using reverse() for In-Place List Reversal
- Time and Space Complexity of Python List reverse()
- Pros of reverse methods:
- Cons of reverse() method:
- When to use reverse() methods ?
- Using Slicing For Python List Reversal
- Pros of list slicing for list reversal:
- Cons:
- When to use slicing or Python List Reversal:
- Using reversed() for Python list reversal
- Pros of reversed() for list reversal:
- Cons:
- Common List Reversal Problems
- How to reverse a list in python using for loop ?
- How to reverse python list using recursion ?
- How to reverse part(subset or slice) of Python list?
- How to reverse Python Numpy Array?
- Summary
- So, which is the best way to reverse list in python?
Python Reverse List with Slicing — An Illustrated Guide
Summary: The slice notation list[::-1] with default start and stop indices and negative step size -1 reverses a given list .
Problem: Given a list of elements. How to reverse the order of the elements in the list.
Example: Say, you’ve got the following list:
Your goal is to reverse the elements to obtain the following result:
Slicing with Default Start and Stop Values
Slicing is a concept to carve out a substring from a given string.
Use slicing notation s[start:stop:step] to access every step -th element starting from index start (included) and ending in index stop (excluded).
All three arguments are optional, so you can skip them to use the default values ( start=0 , stop=len(lst) , step=1 ). For example, the expression s[2:4] from string ‘hello’ carves out the slice ‘ll’ and the expression s[:3:2] carves out the slice ‘hl’ . Note that slicing works the same for lists and strings.
You can use a negative step size (e.g., -1) to slice from the right to the left in inverse order. Here’s how you can use this to reverse a list in Python:
# Reverse a List with Slicing names = ['Alice', 'Bob', 'Carl', 'Dora'] names = names[::-1] print(names) # ['Dora', 'Carl', 'Bob', 'Alice']
Python masters know slicing from the inside out. Do you want to improve your slicing skills? Check out my book “Coffee Break Python Slicing” that will make you a slice pro in no time!
Alternatives Reversing List
Alternatively, you can also use other methods to reverse a list.
- list.reverse() — Best if you want to reverse the elements of list in place.
- list[::-1] — Best if you want to write concise code to return a new list with reversed elements.
- reversed(list) — Best if you want to iterate over all elements of a list in reversed order without changing the original list.
The method list.reverse() can be 37% faster than reversed(list) because no new object has to be created.
Try it yourself in our interactive Python shell:
Exercise: Run the code. Do all methods result in the same reversed list?
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.
Be on the Right Side of Change 🚀
- The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. 🤖
- Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
- Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.
Learning Resources 🧑💻
⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!
Join the Finxter Academy and unlock access to premium courses 👑 to certify your skills in exponential technologies and programming.
New Finxter Tutorials:
Finxter Categories:
How to Reverse Python Lists | In-place, slicing & reversed()
Python lists can be reversed using built-in methods reverse(), reversed() or by [::-1] list slicing technique. The reverse() built-in method reverses the list in place while the slicing technique creates a copy of the original list. The reversed() method simply returns a list iterator that returns elements in reverse order.
Below are the three built-in, common method used for reversing Python lists.
1. Reversing lists in-place using reverse()
>>> nums = [1,2,3,4,5,6,7,8] >>> type(nums.reverse()) type 'NoneType'> >>> nums [8, 7, 6, 5, 4, 3, 2, 1] >>>
2. Reversing lists using slicing (creates a new copy)
>>> nums = [1,2,3,4,5,6,7,8] >>> >>> nums_reversed = nums[::-1] >>> nums_reversed [8, 7, 6, 5, 4, 3, 2, 1] >>> type(nums_reversed) type 'list'> >>> >>> nums [1, 2, 3, 4, 5, 6, 7, 8] >>>
3. Reversing lists using reversed
>>> nums = [1,2,3,4,5,6,7,8] >>> reversed(nums) >>> >>> [n for n in reversed(nums)] [8, 7, 6, 5, 4, 3, 2, 1] >>>
Let us look at each in detail to understand pros, cons and when to use a particular method.
Using reverse() for In-Place List Reversal
>>> nums = [1,2,3,4,5,6,7,8] >>> type(nums.reverse()) type 'NoneType'> >>> nums [8, 7, 6, 5, 4, 3, 2, 1] >>>
Time and Space Complexity of Python List reverse()
The reverse() method works in O(n) time complexity and with O(1) space. Internally, when reverse() is called it operates by swapping i-th element with (n-i)th element. Therefore, the first element is replaced with the last element, the second element is replaced with the second last element and so on. Thus, a total of N/2 swap operations are required for list reversal. That makes the overall time complexity as O(N/2) which is same as O(N)
Pros of reverse methods:
Cons of reverse() method:
When to use reverse() methods ?
Scenarios where order of elements in the original list can be altered and keeping a low memory footprint is desired .
Using Slicing For Python List Reversal
Python lists can be reversed using the [::-1] slicing suffix. It creates and returns a new copy of the list without altering the actual list.
>>> nums = [1,2,3,4,5,6,7,8] >>> >>> nums_reversed = nums[::-1] >>> nums_reversed [8, 7, 6, 5, 4, 3, 2, 1] >>> type(nums_reversed) type 'list'> >>> >>> nums [1, 2, 3, 4, 5, 6, 7, 8] >>>
What does [::-1] notation mean? It means to select elements starting from the first element till the last element with a stride of negative one, i.e, in reverse order. The list slicing notation is [start:end:step], so here start=end=None means the defaults (0 and n-1) and step=-1 implies reverse order.
What are the pros, cons of using slicing for list reversal, and when should we prefer slicing over reverse() or reversed() ?
Pros of list slicing for list reversal:
- The original list is not altered. The order of elements in the original arrays is maintained before and after the slicing operation.
Cons:
- Takes extra space by creating a list of the same size.
- While [::-1] notation is shorter, it is cryptic and requires more attention to understand as compared to english words syntax reverse() or reversed(). In short not the best for code readability.
When to use slicing or Python List Reversal:
- If it is a requirement to preserve the order of elements in the original list.
- It is fine to allocate extra memory for the copy of the list.
Using reversed() for Python list reversal
Python lists can also be reversed using the built-in reversed() method. The reversed() method neither reverses the list in-place nor it creates a copy of the full list. It instead returns a list iterator(listreverseiterator) that generates elements of the list in reverse order.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
>>> nums = [1,2,3,4,5,6,7,8] >>> reversed(nums) >>> >>> [n for n in reversed(nums)] [8, 7, 6, 5, 4, 3, 2, 1] >>> >>> >>> def reverse_python_list(nums): . for num in reversed(nums): . yield num . >>> >>> list(reverse_python_list([1,2,3,4,5,6,7,8])) [8, 7, 6, 5, 4, 3, 2, 1] >>>
Note that calling reversed(nums) simply returns an iterator object. We can see in the following example that the reverse_python_list method, which simply wraps the reversed() method, does not modify the original list or create a copy of the list.
Pros of reversed() for list reversal:
- No extra space is required
- The original list remains unchanged
- The syntax aids to code readability
Cons:
- None really. Just that extra caution needs to be exercised with iterators.The returned iterator can be used only once(it gets exhausted on looping over once). So, if it is required to access the reversed list multiple times, we need to create a copy of the list or call the reversed() function multiple times.
Common List Reversal Problems
Let us take a look at a few other common Python Lists reversal related problems.
How to reverse a list in python using for loop ?
To reverse a list of size n using for loop, iterate on the list from (n-1)th element to the first element and yield each element.
>>> def reverse_list_using_for(nums): . # Traverse [n-1, -1) , in the opposite direction. . for i in range(len(nums)-1, -1, -1): . yield nums[i] . >>> >>> print list(reverse_list_using_for([1,2,3,4,5,6,7])) [7, 6, 5, 4, 3, 2, 1] >>>
How to reverse python list using recursion ?
To reverse a list of using recursion, we define a method that returns sum of two lists, the first being the last element (selected by -1 index) and the second one being reverse of the entire list upto the last element (selected by :-1). The base condition is met when all the elements are exhausted and the array is empty, upon which we return an empty array. Below is the functional code.
>>> def reverse_list_using_recursion(nums): . if not nums: . return [] . return [nums[-1]] + reverse_list_using_recursion(nums[:-1]) . >>> >>> print reverse_list_using_recursion([1,2,3,4,5,6,7]) [7, 6, 5, 4, 3, 2, 1] >>>
How to reverse part(subset or slice) of Python list?
To reverse a part of a list, the built-in reverse, reversed or slicing methods can be used on the subset identified by slicing. The following code shows all the three approaches:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
>>> nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> # Method: 1 Using Slicing >>> nums[3:8][::-1] [8, 7, 6, 5, 4] >>> >>> # Method: 2 Using reverse() >>> nums_subset = nums[3:8] >>> nums_subset.reverse() >>> nums_subet [8, 7, 6, 5, 4] >>> >>> # Method: 3 Using reversed() >>> list(reversed(nums[3:8])) [8, 7, 6, 5, 4] >>>
How to reverse Python Numpy Array?
The numpy arrays can be reversed using the slicing technique (using [::-1] slice descriptor) or by using numpy’s flipud method. The following code shows the usage of both:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
>>> np_array = np.array([1, 2, 3, 4, 5, 6]) >>> # Method 1: Using slicing >>> np_array[::-1] array([6, 5, 4, 3, 2, 1]) >>> type(np_array[::-1]) type 'numpy.ndarray'> >>> >>> # Method 1: Using flipud >>> np.flipud(np_array) array([6, 5, 4, 3, 2, 1]) >>> type(np.flipud(np_array)) type 'numpy.ndarray'> >>>
Summary
In this tutorial we learnt the three techniques for Python list reversal, viz reverse(), reversed() and slicing. We also looked at the pros and cons of each method.
So, which is the best way to reverse list in python?
The answer depends on the requirements. If the requirement is to maintain the order of original elements then reversed() or slicing technique should be used. If the requirement is to have minimal memory footprint, reverse() or reversed() are more suited. If it is required to have a minimal memory footprint along with maintaining order of elements in the original list, reversed() should be used. In general, if there is no such preference, reverse() or reversed() can be preferred over slicing technique as it aids to code readability.