How to Reverse a List in One Line Python | Quick Guide
You can reverse a list in one line in Python using
reversed() function or list slicing with list[::-1]. Both methods create a reversed version of the list quickly and simply.Syntax
There are two common one-line ways to reverse a list in Python:
reversed_list = reversed(original_list)returns an iterator that goes through the list backwards.reversed_list = original_list[::-1]uses slicing to create a new list with elements in reverse order.
The slicing syntax list[start:stop:step] with step = -1 means start from the end and move backwards.
python
reversed_list = reversed(original_list)
reversed_list = original_list[::-1]Example
This example shows how to reverse a list using both methods and print the results.
python
original_list = [1, 2, 3, 4, 5] # Using reversed() returns an iterator, so convert to list to see output reversed_with_function = list(reversed(original_list)) # Using slicing creates a new reversed list reversed_with_slice = original_list[::-1] print(reversed_with_function) print(reversed_with_slice)
Output
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
Common Pitfalls
One common mistake is forgetting that reversed() returns an iterator, not a list. You need to convert it with list() to see or use the reversed list directly.
Another mistake is trying to reverse the list in place with slicing, which does not modify the original list but creates a new one.
python
# Wrong: reversed() returns iterator, not list original = [1, 2, 3] rev = reversed(original) print(rev) # Prints iterator object, not reversed list # Right: convert to list rev_list = list(reversed(original)) print(rev_list) # Wrong: slicing does not change original list original[::-1] print(original) # Original list unchanged # Right: assign slicing result reversed_list = original[::-1] print(reversed_list)
Output
<list_reverseiterator object at 0x7f...>
[3, 2, 1]
[1, 2, 3]
[3, 2, 1]
Quick Reference
Use this quick guide to remember how to reverse lists in one line:
| Method | Code | Notes |
|---|---|---|
| Using reversed() | list(reversed(my_list)) | Returns a reversed iterator, convert to list |
| Using slicing | my_list[::-1] | Creates a new reversed list, original unchanged |
Key Takeaways
Use
my_list[::-1] to quickly get a reversed copy of a list in one line.The
reversed() function returns an iterator, so wrap it with list() to get a list.Slicing with
::-1 does not change the original list but returns a new reversed list.Remember to convert the iterator from
reversed() before printing or using it as a list.