Table of Contents
The reversed() function returns the reversed iterator of the given sequence.
The syntax of reversed() is:
reversed(seq)
1. reversed() Parameters
The reversed() function takes a single parameter:
- seq – the sequence to be reversed
A sequence is an object that supports sequence protocols: __len__() and __getitem__() methods. For example, tuple, string, list, range, etc.
We can also use reversed() in any object that implements __reverse__().
2. Return value from reversed()
The reversed() function returns an iterator that accesses the given sequence in the reverse order.
3. Example 1: Using reveresed() in string, tuple, list, and range
# for string
seq_string = 'Python'
print(list(reversed(seq_string)))
# for tuple
seq_tuple = ('P', 'y', 't', 'h', 'o', 'n')
print(list(reversed(seq_tuple)))
# for range
seq_range = range(5, 9)
print(list(reversed(seq_range)))
# for list
seq_list = [1, 2, 4, 3, 5]
print(list(reversed(seq_list)))
Output
['n', 'o', 'h', 't', 'y', 'P'] ['n', 'o', 'h', 't', 'y', 'P'] [8, 7, 6, 5] [5, 3, 4, 2, 1]
In our example, we have converted the iterators returned by reversed() to list using the list() function.
4. Example 2: reversed() in custom objects
class Vowels:
vowels = ['a', 'e', 'i', 'o', 'u']
def __reversed__(self):
return reversed(self.vowels)
v = Vowels()
print(list(reversed(v)))
Output
['u', 'o', 'i', 'e', 'a']
Related posts:
Python Set symmetric_difference()
Python Program to Print Output Without a Newline
Python del Statement
Python Program to Remove Duplicate Element From a List
Python Set remove()
Python Program to Count the Occurrence of an Item in a List
Python classmethod()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Keywords and Identifiers
Python Package
Python Set difference_update()
Python Program to Print Colored Text to the Terminal
Python String isnumeric()
Python Program to Safely Create a Nested Directory
Python Program to Print the Fibonacci sequence
Python Closures
Python Program to Get the Last Element of the List
Python Program to Get File Creation and Modification Date
Python staticmethod()
Python Program to Convert Two Lists Into a Dictionary
Python String isprintable()
Python divmod()
Python Program to Split a List Into Evenly Sized Chunks
Python Program to Find the Factors of a Number
Python Program to Check the File Size
Python List insert()
Python if...else Statement
Python Errors and Built-in Exceptions
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python property()
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python String lstrip()