×


Python List reverse() - An overview ?



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 LinuxAPT, 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:

list_name.reverse()


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']
animals.reverse()
print(animals)
When you run this program, the output will look like this:
['elephant', 'dog', 'cat']


2. Reverse an OS list:

systems=['windows', 'mac', 'linux']
# Reverse
systems.reverse()
print(systems)

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
print(reversed)

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):
print(n)

Its Output will look like this:

e
d
c
b
a


[Need assistance in fixing Python list issues? We can help you. ]


Conclusion

This article covers a detailed instructions on how to use the reverse() method and a few ways to reverse a list in Python. In fact, Python List reverse() function allows the programmer to reverse the sorting order of the elements stored in the lists.


More Linux Tutorials

We create Linux HowTos and Tutorials for Sys Admins. Visit us on IbmiMedia.com

Also for Tech related tips, Visit forum.outsourcepath.com or General Technical tips on www.outsourcepath.com