The Wayback Machine - http://web.archive.org/web/20220817193000/https://www.geeksforgeeks.org/python-reversed-function/amp/

Python reversed() function

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.




# 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




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()




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

Output:

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

Example 4: Python reverse() string




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




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

Output:

[5, 3, 4, 2, 1]



Article Tags :
Practice Tags :