Python List reverse

Posted 

2 min read

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:

list.reverse()

reverse() doesn’t accept arguments.

Here is an example:

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

capitals.reverse()

print('Reversed list:', capitals)
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:

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:

numbers = [1, 2, 3, 4]

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

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

numbers = [1, 2, 3, 4]

print(list(reversed(numbers)))
[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:

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.

[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.