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 Get Current time
Python abs()
Python Program to Count the Number of Occurrence of a Character in String
Python Program to Calculate the Area of a Triangle
Python Variables, Constants and Literals
Python Program to Check the File Size
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python any()
Python slice()
Python List append()
Python memoryview()
Python Program to Check Armstrong Number
How to get current date and time in Python?
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Program to Get a Substring of a String
Python complex()
Python del Statement
Python Program to Get the Full Path of the Current Working Directory
How to Get Started With Python?
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python chr()
Python dir()
Python Program to Catch Multiple Exceptions in One Line
Python locals()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python ord()
Python String casefold()
Python List index()
Python List insert()
Python range()
Python strptime()