Python has a built-in reverse() function in order to reverse the contents stored in the list. The name of this function is Python list reverse() which is used only for the list data type. Python reverse list method does not create a new list, but in turn, it directly modifies the existing list to it in the reverse order. 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.
Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform related Python list queries.
In this context, we shall look into how to use the reverse() method and some ways to reverse a list in Python.
What is List reverse() in Python ?
The reverse() method helps to reverse the sort order of the elements.
Its syntax is given below:
A few examples of List reverse() in Python
1. Reverse the order of the animal list
Here, we will try to reverse the order of the animal list:
animals = ['cat', 'dog', 'elephant']
When you run this program, the output will look like this:
['elephant', 'dog', 'cat']
2. Reverse an OS list:
systems=['windows', 'mac', 'linux']
Its output will look like this:'
['linux', 'mac', 'windows']
3. 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
Its output will look like this:
[5, 4, 3, 2, 1]
4. Use the reversed() function to reverse
list = ['a', 'b', 'c', 'd', 'e']
# Reverse the list
for n in reversed(list):
Its Output will look like this:
[Need assistance in fixing Python list issues? We can help you. ]