Scripting

Python List reverse()

list_name.reverse()

Introduction

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.

Example

I will try to reverse the order of the animal list:

animals = ['cat', 'dog', 'elephant']

animals.reverse()

print(animals)

Output:

[‘elephant’, ‘dog’, ‘cat’]

Definition

The reverse() method helps to reverse the sort order of the elements.

The syntax

list_name.reverse()

Explained:

list_name: name of the list

reverse(): this helps reverse the list

More example

Example 1: Reverse a list:

systems=['windows', 'mac', 'linux']

# Reverse

systems.reverse()

print(systems)

Output:

[‘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)

Output:

[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)

Output:

e

d

c

b

a

Conclusion

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.

Similar Posts