PythonPython ListsList reversal
How do you reverse a list?
Question 87 of 88 · Updated
On this page
Use items.reverse() to reverse the original list, items[::-1] to create a reversed copy, or reversed(items) to iterate backward without creating a new list.
Practical example: Show recent activity first#
PYTHONactivity = ['first', 'second', 'third'] print(activity[::-1]) # ['third', 'second', 'first'] print(list(reversed(activity))) # ['third', 'second', 'first'] activity.reverse() print(activity) # ['third', 'second', 'first']
The first two operations leave the original list unchanged. The final operation reverses it in place.
Quick comparison#
| Method | Changes original? | Returns | Best for |
|---|---|---|---|
| reverse() | Yes | None | Reordering an existing list |
| reversed() | No | Reverse iterator | Looping backward |
| [::-1] | No | New list | Keeping a reversed copy |
Which method should you choose?#
Use reverse() if the existing order is no longer needed. Use slicing when you want both the original and reversed lists. Use reversed() when you only need to visit elements backward, such as displaying recent activity.
A reverse iterator is consumed as you iterate over it. It is not a snapshot, so avoid changing the source list during traversal.
Common mistakes#
- Do not assign the result of reverse() to your list variable: it returns None.
- reversed() does not directly return a list; use list(reversed(items)) if a list is needed.
- Reversing is not descending sorting. Reversing [3, 1, 2] gives [2, 1, 3], not [3, 2, 1].
For an ordinary CPython list, reverse() takes O(n) time and O(1) extra space. Slicing takes O(n) time and extra reference storage. Creating a reverse iterator takes O(1) space; traversing it fully takes O(n) time.
Official references#
References
- 1.Mutable sequence typesdocs.python.org
- 2.Python reversed()docs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design