Python reversed() function is used to Reverse the sequence of a list or other iterator object. This function actually returns the reversed iterator of the given sequence and takes a single parameter.
The syntax of reversed() is:
reversed(seq)
Python reversed() function examples
Simple example code Reverse the sequence of a list, and print each element:
list1 = ["A", "B", "C", "D"]
res = reversed(list1)
for x in res:
print(x)
Output:
Print reversed list
list1 = ["A", "B", "C", "D"]
print(list(reversed(list1)))
Output: [‘D’, ‘C’, ‘B’, ‘A’]
Using reversed() 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]
Do comment if you have any doubts or suggestions on this Python functions basic topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.