Python reversed() Method
reversed() function in Python lets us go through a sequence like a list, tuple or string in reverse order without making a new copy. Instead of storing the reversed sequence, it gives us an iterator that yields elements one by one, saving memory. Example:
a = ["nano", "swift", "bolero", "BMW"]
print(list(reversed(a)))
Output
['BMW', 'bolero', 'swift', 'nano']
Explanation: The list a is passed to reversed(), which returns an iterator. The list() convert the iterator into a list and display the reversed order.
Syntax of reversed()
reversed(sequence)
Parameter: input sequence that needs to be reversed. It must be an iterable such as a list, tuple, string or range.
Returns: an iterator that produces the elements of the sequence in reverse order.
Note: reversed() function does not work with sets because they are unordered collections.
Examples of reversed()
Example 1: Using reversed() with tuples and ranges
# For tuple
tup = ('g', 'e', 'e', 'k', 's')
print(list(reversed(tup)))
# For range
r = range(1, 5)
print(list(reversed(r)))
Output
['s', 'k', 'e', 'e', 'g'] [4, 3, 2, 1]
Explanation: The tuple tup and range r are passed to reversed(), which returns an iterator. The list() converts it into a list, displaying the reversed sequence. The tuple's characters appear in reverse and range(1,5) producing [1, 2, 3, 4] results in [4, 3, 2, 1].
Example 2: Using reversed() in a for loop
s = "Python is great"
# reverse the string
for char in reversed(s):
print(char, end="")
Output
taerg si nohtyP
Explanation: The for loop iterates over the reversed string, printing characters in reverse without a newline, displaying the string in a single line.
Example 3: Reversing a string as a list
s = "Geeksforgeeks"
print(list(reversed(s)))
Output
['s', 'k', 'e', 'e', 'g', 'r', 'o', 'f', 's', 'k', 'e', 'e', 'G']
Explanation: string s is passed to reversed(), which returns an iterator. The list() converts it into a list of characters in reverse order.
Handling Exception in reversed()
If we try to fetch elements from the iterator beyond its range, a StopIteration exception occurs.
a = [1, 2, 3]
# Reverse the list
b = reversed(a)
# Print the reversed elements one by one using the `next` function
print(next(b))
print(next(b))
print(next(b))
print(next(b)) # Exception
Output
3
2
1
StopIteration
print(next(my_list_rev)) # Exception
Line 11 in <module> (Solution.py)
Explanation: list a is passed to reversed(), returning an iterator b. The next() function retrieves 3, 2, and 1. Calling next(b) again raises a StopIteration exception as the iterator is exhausted.
original_tuple = (1, 2, 3, 4, 5)
reversed_tuple = tuple(reversed(original_tuple))
print(reversed_tuple) # Output: (5, 4, 3, 2, 1)
- Tuples: Yes, you can use reversed() with tuples, and it will return an iterator.
- Sets: No, you cannot use reversed() with sets because sets are unordered collections and do not maintain any specific order.