Reversed Function In Python

Overview:

  • The reversed() built-in function returns a reverse iterator for a given sequence.
  • The reversed() function works for objects that implements the __reversed__() method or objects that implements the sequence protocol.
  • The reversed() function works for sequences(which are also iterables) like lists, tuples and iterables(which are not sequences) like dictionaries. 
  • On a dictionary object calling reversed()is equaivalent to calling the reversed() for the dict.keys() and dict_keys returned by dict.keys()acts like a list for the most part though it is not indexable.  
  • The reversed() function does not work on generators.

Example 1:

# Example Python program that uses
# a reverse iterator obtained from a Python list
# and prints the list in the reverse order
squares = [1, 4, 9, 16, 25]

# Obtain a reverse iterator
rIter = reversed(squares)

# Print items of the list through a reverse iterator
print("List elements:")
for num in rIter:
    print(num)

print(type(rIter))

Output:

List elements:

25

16

9

4

1

<class 'list_reverseiterator'>

Example 2:

# The reversed() function used to print the keys of a Python dictionary 
# in reverse order

# Create a Python dictionary
pairs = {"a":1, "b":2, "1a":11, "b9":29}

# Get a reverse iterator
ri = reversed(pairs)

# Print the keys of the dictionary
# Note that iteritems() and items() will not work on the
# reverse iterator obtained on the dictionary
print("Dictionary keys:")
for key in ri:
    print(key)

print(type(ri))

Output:

Dictionary keys:

b9

1a

b

a

<class 'dict_reversekeyiterator'>

Example 3:

# Example Python program that tries to
# get a reverse iterator on a generator
exp = (n*n for n in range(0,5))

# Try getting a reverse iterator and print values from the generator
# (This will fail as generators are not sequences - no length
# and not subscriptable)  
ri = reversed(exp);

for num in ri:
    print(num)

Output:

Traceback (most recent call last):

  File "/ex/reversed_gen.py", line 8, in <module>

    ri = reversed(exp);

TypeError: 'generator' object is not reversible

 


Copyright 2023 © pythontic.com