Python list.reverse() Method

The list.reverse() method in Python is used to get the elements in reverse. This function doesn’t take any parameters and doesn’t return anything. This function is called on the list object, post execution the elements on the original list object are reversed.

1. Python List reverse() Method Syntax

Following is the syntax of the list reverse() method.


#Syntax
list.reverse()

1.1 Parameters

This reverse() function doesn’t take any parameters.

1.2 Return Type

The reverse() method doesn’t return anything and reverses the elements in the original list.

2. Reverse List using reverse() Method

The reverse() is a method in Python list that will reverse elements in the list. The below examples take the list of strings and reverse the elements in the list.


# Consider list of countries
countries=["India","China","Russia","China"]
print("Actual List: ",countries)

# Using reverse()
countries.reverse()
print("Reversed List: ",countries)

This example yields the below output.

python list reverse method

3. Reverse List of Numbers

The above example covers everything about the list, however, I would like to cover one example of reversing lists with numbers.


# Consider list of numbers
numbers=[4,6,8,10,12]
print("Actual List: ",numbers)

# Using reverse()
numbers.reverse()
print("Reversed List: ",numbers)

This example yields the below output.


# Output:
Actual List:  [4, 6, 8, 10, 12]
Reversed List:  [12, 10, 8, 6, 4]

Conclusion

In this article, you have learned the syntax of the reverse() method from the python list which ideally reverses the elements in the list. This function doesn’t take any parameters and returns nothing. You need to call this function on the list object, post execution the elements in the list are reversed.

Besides this method, there are Different ways to Reverse Elements in List. Alternatively, you can also reverse the iterable objects by using the built-in function reversed()

NNK

SparkByExamples.com is a Big Data and Spark examples community page, all examples are simple and easy to understand and well tested in our development environment Read more ..

Leave a Reply