This guide deals with the Python reversed function and it’s uses, complete with several examples.
The Python reversed function provides us with a quick and easy way to reverse the order of all the elements in a sequence. It takes as input an appropriate sequence, such as a list, and returns an iteratable object.
Syntax
reversed(sequence)
There is a slight catch however. Sequences like dictionaries do not have order. Dictionaries are unordered collections of data, using keys to identify their values. Hence, they cannot be reversed. Examples of sequences that can be reversed are lists, tuples, sets, strings, the range() sequence and more.
Example Set 1:
Since the reversed function returns a iteratable object, to get it to display in a readable format, we need to wrap it in the list()
function. This will return a list object, identical to the original, but reversed in order.
X = [3,4,5]
B = reversed(X)
print(list(B))
X = (2,7,4,1)
B = reversed(X)
print(list(B))
[5, 4, 3]
[1, 4, 7, 2]
Example Set 2
You can however use the returned iteratable object directly in a loop. Iterate over it, and print out each element individually.
X = [3,4,5]
B = reversed(X)
for x in B:
print(x)
5
4
3
This marks the end of the Python reversed Function Article. Any suggestions or contributions for CodersLegacy are more than welcome. Any questions can be asked in the comments section below.
Head back to the main Built-in Functions Article using this link.