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.
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()
Related Articles
- Add 1 to each Element in the List in Python
- Python Doubly Linked List with Examples
- How to Prepend to a List
- Python Print List without Brackets
- Get Index of Max of List in Python
- Python Split a list into evenly sized chunks?
- Python zip() Two Lists with Examples
- Concatenate List of Strings Python
- Python difference between __str__ and __repr__?
- Using “if else” in a List Comprehension
- Python reversed() Function with Examples
- Relative Imports in Python 3