
In this post you will learn How to reverse a list in Python.
reverse method in python –
To reverse a list in python we can use the reverse method.
Syntax of reverse –
list.reverse()
The reverse method does not take any arguments and does not return anything. It changes the list in place.
Reverse a List –
In [1]: companies = ['Google','Facebook','Apple','Microsoft','Amazon']
In [2]: companies.reverse()
In [3]: companies
Out[3]: ['Amazon', 'Microsoft', 'Apple', 'Facebook', 'Google']
Reverse a List using slicing in python –
If you want, you can also reverse a list using slicing in python
In [5]: companies
Out[5]: ['Amazon', 'Microsoft', 'Apple', 'Facebook', 'Google']
In [6]: companies[::-1]
Out[6]: ['Google', 'Facebook', 'Apple', 'Microsoft', 'Amazon']
Accessing a List in reverse order –
If you just want to access the elements of a list in reverse order without reversing the list itself then you can use the reversed() function.
In [7]: companies
Out[7]: ['Amazon', 'Microsoft', 'Apple', 'Facebook', 'Google']
In [8]: for company in reversed(companies):
...: print(company)
...:
Google
Facebook
Apple
Microsoft
Amazon
In [9]: