Python List reverse() Method



The Python List reverse() method reverses a list. That means, the first object in the list becomes the last object and vice versa.

Another common technique used to reverse a string is done using the slicing operator with the syntax [::-1]. However, there is a need to create another list to store the reversed list as this operator will not modify the original list. To overcome this, the reverse() method is used; it will reverse the original string instead of creating another list.

Syntax

Following is the syntax for the Python List reverse() method −

list.reverse()

Parameters

The method does not accept any parameters.

Return Value

This method does not return any value but reverse the given object from the list.

Example

The following example shows the usage of the Python List reverse() method.

aList = [123, 'xyz', 'zara', 'abc', 'xyz']
aList.reverse()
print("List : ", aList)

When we run above program, it produces following result −

List :  ['xyz', 'abc', 'zara', 'xyz', 123]

Example

When we try to reverse an empty list, the method returns a None value.

In this example, we are creating a list with no elements in it. The reverse() method is called on this list and since it has no elements, None is returned.

aList = []
print("Reversed List : ", aList.reverse())

Let us compile and run the program above, the output is displayed as follows −

Reversed List :  None

Example

In real-time Python applications, we can use this method to check whether a given string is a palindrome or not.

As it is not a string method, we are first converting a string object into a list using the list() method and this list is copied to another list using the copy() method. The original list is then reversed using the reverse() method and these two lists are compared to check whether they are equal or not.

str = "malayalam"
list1 = list(str)

# Copy the list in another list using copy() method
list2 = list1.copy()

# Reverse the list using the reverse() method
res = list1.reverse()

if list1 == list2:
    print("The string is a palindrome")
else:
    print("The string is not a palindrome")

On executing the program above, the output is as follows −

The string is a palindrome
python_lists.htm
Advertisements