The reverse() method in Python reverses the arrangement of the objects in the list. This method returns no value.
Reversing a list is a necessary operation in Python programming. For example, you have a list of student names in the correct alphabet (A-Z) but some people want to see the reverse. And now the list reversal has come into play. Below is the guide on how to use the reverse() method and some ways to reverse a list in Python as we go through below.
I will try to reverse the order of the animal list:
animals = ['cat', 'dog', 'elephant'] animals.reverse() print(animals)
[‘elephant’, ‘dog’, ‘cat’]
The reverse() method helps to reverse the sort order of the elements.
list_name: name of the list
reverse(): this helps reverse the list
Example 1: Reverse a list:
systems=['windows', 'mac', 'linux'] # Reverse systems.reverse() print(systems)
[‘linux’, ‘mac’, ‘windows’]
Example 2: Reverse a list using a slicing list [::-1]
number = [1, 2, 3, 4, 5] # Add [::-1] after the original list reversed = number[::-1] # Print the result print(reversed)
[5, 4, 3, 2, 1]
Example 3: Use the reversed() function to reverse
list = ['a', 'b', 'c', 'd', 'e'] # Reverse the list for n in reversed(list): print(n)
You have just seen detailed instructions on how to use the reverse() method and some ways to reverse a list in Python.
Thank you for reading.
Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications including CCNA RS, SCP, and ACE. As an IT engineer and technical author, he writes for various websites.