In this article, we will discuss the usage details of reverse() method of Python list.
Table Of Contents
In pattern the list class provides a method reverse(), it reverses the contents of the calling list object in place.
Syntax of list reverse
The reverse() method of list does not accept any parameter.
The reverse() method of list does not return anything. Basically the return value will be
Let’s see some examples
Example 1 of List reverse() method
Suppose we have a list of numbers and we want to reverse the order of numbers in the list. Like, instead of numbers from 90 to 95 our list should have numbers in reverse order that is 95 to 90. We can do that by simply calling the reverse() function on the list. For example,
listOfNumbers = [90, 91, 92, 93, 94, 95] # reverse the order of elements in list listOfNumbers.reverse() print(listOfNumbers)
[95, 94, 93, 92, 91, 90]
The reverse() method modified the calling list object by reversing the order of the elements in it.
Example 2 of List reverse() method
Suppose we have a list of strings and we want to reverse the order of strings in this list. For that we will again call the reverse() function on the list object. Let us see the example,
listOfStrings = ["is", "at", "what", "how", "the"] # reverse the order of elements in list listOfStrings.reverse() print(listOfStrings)
['the', 'how', 'what', 'at', 'is']
It reversed the order of strings in the list. All the strings remained same, but the order in which they appear in the list got reversed.
We learned all about the reverse() method of List in Python.