Python List reverse

By 

Published on

2 min read

Reverse a List in Python

When working with lists in Python, you may sometimes need to reverse the elements of a list. Reversing a list means that the first element of the list becomes the last, the second become second-to-last, the last element becomes the first, and so on.

In Python, there are several different ways to reverse a list, depending on what you’re trying to do.

reverse() method

reverse() is a list data type method that reverses the elements of the list in-place. This method modifies the original list rather than creating a new one.

The syntax of the reverse() method is as follows:

python
list.reverse()

reverse() doesn’t accept arguments.

Here is an example:

python
capitals = ['Oslo', 'Skopje', 'Riga', 'Madrid']

capitals.reverse()

print('Reversed list:', capitals)
output
Reversed list: ['Madrid', 'Riga', 'Skopje', 'Oslo']

reversed() function

reversed() is a Python built-in function that returns a reversed iterator of a given iterable object. The original list is not modified.

If you only want to iterate over the list’s elements in reverse order prefer using the reversed() function, as it is faster than reversing the elements in place.

The syntax of the reversed() function is as follows:

python
reversed(seq) 

Where seq is the list you want to revert.

Below is an example using reversed() to loop over the elements of list in reversed order:

python
numbers = [1, 2, 3, 4]

for i in reversed(numbers) :
    print(i)
output
4
3
2
1

If you want to convert the reversed iterator into a list, use the list() constructor:

python
numbers = [1, 2, 3, 4]

print(list(reversed(numbers)))
output
[4, 3, 2, 1]

Reverse a List using Slicing

Slice notation is a Python built-in feature that allows you to extract parts of a sequential data type. Although not very Pythonic, you can use the [::-1] notation reverse a list:

python
numbers = [1, 2, 3, 4]

print(numbers[::-1])

The result of slicing a list is a new list containing the extracted elements. The original list is not modified.

output
[4, 3, 2, 1]

Conclusion

To reverse a Python list in place, use the reverse() method. If you only need to create a reversed iterator, use the reversed() function.

If you have any questions or feedback, feel free to leave a comment.

Tags

Linuxize Weekly Newsletter

A quick weekly roundup of new tutorials, news, and tips.

About the authors

Dejan Panovski

Dejan Panovski

Dejan Panovski is the founder of Linuxize, an RHCSA-certified Linux system administrator and DevOps engineer based in Skopje, Macedonia. Author of 800+ Linux tutorials with 20+ years of experience turning complex Linux tasks into clear, reliable guides.

View author page