Skip to content
Related Articles

Related Articles

Python reversed() function

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 23 Sep, 2021

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

Python reversed() Syntax

reversed(sequ) 

Python reversed() Parameters

sequ : Sequence to be reversed. 

Python reversed() Returns

returns an iterator that accesses the given sequence in the reverse order. 

How to use the reversed method in Python?

Example 1: Demonstration of Python reversed() method

Here we use tuple and range.

Python3




# Python code to demonstrate working of
# reversed()
 
# 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]

Example 2: reversed() in custom objects

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']

Example 3: Python List reverse()

Python3




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

Output:

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

Example 4: Python reverse() string

Python3




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

Output:

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

Example 5: Python reverse() list

Python3




# For list
seqList = [1, 2, 4, 3, 5]
print(list(reversed(seqList)))

Output:

[5, 3, 4, 2, 1]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!