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
- Using the “
[::-1]” list slicing to create a reversed copy
- Creating a reverse iterator with the
Example reverse a list in Python
Simple example code.
This method doesn’t return any value and updates the existing list.
num = [2, 3, 5, 7] num.reverse() print(num)
Using the “[::-1]” Slicing Trick to Reverse a Python List
List slicing uses the “
” indexing syntax with the following “
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)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.