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 # Obtain a reverse iterator # Print items of the list through a reverse iterator 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 # Create a Python dictionary # Get a reverse iterator # Print the keys of the dictionary print(type(ri)) |
Output:
Dictionary keys: b9 1a b a <class 'dict_reversekeyiterator'> |
Example 3:
# Example Python program that tries to # Try getting a reverse iterator and print values from the generator for num in ri: |
Output:
Traceback (most recent call last): File "/ex/reversed_gen.py", line 8, in <module> ri = reversed(exp); TypeError: 'generator' object is not reversible |