How to reverse a list in Python | Example code

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.

  1. Reversing a list in-place with the list.reverse() method
  2. Using the “[::-1]” list slicing to create a reversed copy
  3. 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:

How to reverse a list in Python

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 and suggestions on this Python reverse list topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.