Lists are an important data type in Python that is used in a lot of different ways. At times, you may even need to reverse a particular list in order to implement an algorithm or because of design implementation.
In this article, we’re going over how you can reverse a list in Python. There are three ways you can do this.
Also read: How to create a list in Python?
Using the reverse() function to reverse a list in Python
The reverse() function does exactly what the name suggests. It’s a list type method that reverses the elements in a list. Do keep in mind that this function modifies the original list instead of creating a new one.
The basic syntax of the method is as follows. It doesn’t accept any arguments either.
Here’s an example for your reference.
list = ['Candid', '.', 'Technology'] list.reverse() print(list)
Using the reversed() function to reverse a list in Python
If you don’t want to modify the original list, you can use the reversed() function. The difference between reverse and reversed is that while the former is a list function to reverse lists, the latter returns a reversed iteration of any given iteration object.
In case you don’t want to reverse the list itself but just want to iterate over it in reverse, you should use this method as this is faster than the first one.
The basic syntax for this function is as follows.
Where seq is the sequence to be reversed. Here’s an example.
numbers = [1, 2, 3, 4] for i in reversed(numbers) : print(i)
Also read: How to check Python version?
Slicing to reverse a list in Python
The Slice notation is a Python feature that allows a programmer to extract parts of any sequential data type, in this case, a list. You can use the [::-1] notation to reverse a list.
numbers = [1, 2, 3, 4] print(numbers[::-1])
Also read: How to convert list to string in Python?