Simply using the reverse() method can reverse a list in Python. It’s a built-in function in Python. You can also use the slicing or reversed() function for it.
- Reversing a list in-place with the
list.reverse()
method - Using the “
[::-1]
” list slicing to create a reversed copy - Creating a reverse iterator with the
reversed()
built-in function
Example reverse a list in Python
Simple example code.
List reverse()
This method doesn’t return any value and updates the existing list.
num = [2, 3, 5, 7]
num.reverse()
print(num)
Output:
Using the “[::-1]” Slicing Trick to Reverse a Python List
List slicing uses the “[]
” indexing syntax with the following “[start:stop:step]
” pattern:
lst = [1, 2, 3, 4, 5, 6]
new_lst = lst[::-1]
print(new_lst)
Output: [6, 5, 4, 3, 2, 1]
Using the reversed() built-in function.
This method returns a reverse iterator which we use to cycle through the list.
lst = ["A", "B", "C"]
res = reversed(lst)
print(list(res))
Output: [‘C’, ‘B’, ‘A’]
Do comment if you have any doubts or suggestions on this Python reverse list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.