Open In App

Python reversed() Method

Last Updated : 01 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python reversed() method returns an iterator that accesses the given sequence in the reverse order.

Example:

Python3




# creating a list
cars = ["nano", "swift", "bolero", "BMW"]
# reversing the list
reversed_cars = list(reversed(cars))
#printing the list
print(reversed_cars)


Output

['BMW', 'bolero', 'swift', 'nano']

Python reversed() Method Syntax

reversed(sequence) 

Parameter :

  • sequence : Sequence to be reversed. 

Return : Returns an iterator that accesses the given sequence in the reverse order. 

How to use reversed function in Python?

reversed() method is very easy to use and it returns an iterator that accesses the list in reverse order. Let’s understand it better with an example.

Example:

In the given example, we are reversing elements of the list with reversed() function in Python.

Python3




my_list = ["apple", "banana", "cherry", "date"]
reversed_list = list(reversed(my_list))
print(reversed_list)


Output

['date', 'cherry', 'banana', 'apple']

More Python reversed() Method Examples

Let’s see some of the other common scenarios for reversed() method.

1. Python reversed() with Built-In Sequence Objects

In the given example we have used reversed() with tuple and range. When using reversed with these objects we need to use the list() method to convert the output from reversed() to list.

Python3




# For tuple
seqTuple = ('g', 'e', 'e', 'k', 's')
print(list(reversed(seqTuple)))
  
# For range
seqRange = range(1, 5)
print(list(reversed(seqRange)))


Output

['s', 'k', 'e', 'e', 'g']
[4, 3, 2, 1]

2. Python reversed() with for loop in Python

In this example, we are using reversed() function to show it’s working with Python loops.

Python3




# Create a string
str = "Reversed in Python"
  
# Reverse the string and print its characters in reverse order
for char in reversed(str):
    print(char, end="")


Output

nohtyP ni desreveR

Output

nohtyP ni desreveR

3. Python reversed() in Python with custom objects

In this example, we are creating a class gfg which includes a list of vowels we are using the reversed function to reverse the vowels.

Python3




class gfg:
    vowels = ['a', 'e', 'i', 'o', 'u']
  
    # Function to reverse the list
    def __reversed__(self):
        return reversed(self.vowels)
  
# Main Function    
if __name__ == '__main__':
    obj = gfg()
    print(list(reversed(obj)))


Output

['u', 'o', 'i', 'e', 'a']

4. Python reversed() method with List

In this example, we are reversing a list of vowels with the reversed function in Python.

Python3




vowels = ['a', 'e', 'i', 'o', 'u']
print(list(reversed(vowels)))


Output

['u', 'o', 'i', 'e', 'a']

5. Python reversed() method with string

In this example, we are reversing a string with the reversed function in Python.

Python3




str = "Geeksforgeeks"
print(list(reversed(str)))


Output

['s', 'k', 'e', 'e', 'g', 'r', 'o', 'f', 's', 'k', 'e', 'e', 'G']

Exception in reversed() function

In this example, we are showing the exception in reversed() function.

Python3




# Create a list
lst = [1, 2, 3]
  
# Reverse the list using the `reversed` function
reversed_lst = reversed(lst)
  
# Print the reversed elements one by one using the `next` function
print(next(reversed_lst))  
print(next(reversed_lst))  
print(next(reversed_lst))  
  
# Attempting to print the next element will raise a StopIteration exception
print(next(reversed_lst))  # Exception


Output

3
2
1
StopIteration
print(next(my_list_rev)) # Exception
Line 13 in <module> (Solution.py)

We have covered the definition, syntax and different uses of reversed() method in Python. Python reversed() function is very important function to access sequence from the end.

reversed() method can be used to reverse a set, list,tuple, etc in Python.

Hope this article helped you in your Python journey!



Previous Article
Next Article

Similar Reads

Python | Reversed Split Strings
The functionality of splitting is quite popular with manyfold applications and usages. With all, comes the scopes of many types of variations. This article discusses one among those variations in which one desires to get the split and reversal of element string order, both the operations at once. Let's discuss certain ways to solve this particular
5 min read
Python | Reversed Order keys in dictionary
While working with dictionary, we can sometimes, have a problem in which we require to print dictionaries in the reversed order of their occurrence. Let's discuss certain ways in which this problem can be solved. Method #1 : Using reversed() + sorted() + keys() + loop The combination of above functions can be used to perform this particular task. T
4 min read
Python - K elements Reversed Slice
Given List of elements, perform K elements reverse slice. Input : test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18], K = 3 Output : [18, 16, 15] Explanation : 3 elements sliced from rear end. Input : test_list = [2, 4, 6, 8], K = 3 Output : [8, 6, 4] Explanation : 3 elements sliced from rear end, 8, 6 and 4. Method #1 : Using list slicing This is one
4 min read
Python - Assign Reversed Values in Dictionary
Given a dictionary, assign each key, values after reverting the values of dictionary. Input : {1 : 4, 2 : 5, 3 : 6} Output : {1 : 6, 2 : 5, 3 : 4} Explanation : Value order changed, 4, 5, 6 to 6, 5, 4. Input : {1 : 5, 2 : 5, 3 : 5} Output : {1 : 5, 2 : 5, 3 : 5} Explanation : Same values, no visible change. Method #1 : Using values() + loop + rever
4 min read
Python - reversed() VS [::-1] , Which one is faster?
Python lists can be reversed using many Python method such as using slicing method or using reversed() function. This article discusses how both of these work and Which one of them seems to be the faster one and Why. Reversing a list using SlicingThe format [a : b : c] in slicing states that from an inclusive to b exclusive, count in increments of
3 min read
Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that
4 min read
Difference between Method Overloading and Method Overriding in Python
Method Overloading: Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need of more than one class for method overloading.Note: Python does not support
3 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Article Tags :
Practice Tags :