Python Built-in Function reversed:
The reversed() is an inbuilt function in Python that returns a new sequence object with the elements in reverse order. However, the original sequence will not be updated.
Signature
The signature for the reversed()
function is as shown below. Here, l stores an object that the function returns.
l=reversed(sequence)
Parameters and return type
- This method takes one parameter sequence. This sequence can be a list, tuple, dictionary or, a string.
- However, it returns a reversed object of sequence.
Python Built-in Function reversed Examples:
Example 1: For example, let us initialize a list, and a tuple object with some numbers. Thereafter, we will use the reversed function to reverse the elements. So, it returns the sequence object that has the elements in the reverse order of original sequence. In order to print the values, we have to typecast this to a list or tuple.
#Initializing
l = [159, 254, 11, 8, 4559, 32]
t=(22,4,331,55)
#Using reversed and printing
print("reversed list - ",list(reversed(l)))
print("reversed tuple - ",tuple(reversed(t)))
Output
reversed list - [32, 4559, 8, 11, 254, 159]
reversed tuple - (55, 331, 4, 22)
Example 2: In this example, we will take a string and a dictionary. We will reverse this sequence and print it as a list. As we can see, it takes string as a list of characters and dictionary as a list of keys.
#Initializing
s = "python"
d={1:"One",2:"Two",3:"Three"}
#Using reversed and printing
print("reversed string - ",list(reversed(s)))
print("reversed dictionary - ",list(reversed(d)))
Output
reversed string - ['n', 'o', 'h', 't', 'y', 'p']
reversed dictionary - [3, 2, 1]
Example 3: In this case, let us take a set containing string. It will raise a TypeError exception because set objects cannot be reversed.
#Initializing
city={"chennai", "delhi","mumbai", "hyderabad"}
#Using reversed and printing
print(reversed(city))
Output
Traceback (most recent call last):
File "main.py", line 3, in
print(reversed(city))
TypeError: 'set' object is not reversible
Conclusion
The reversed() function returns a new sequence object with elements in reverse order.
References
Happy Learning 🙂