Python reversed() Function
The reversed()
function returns a reversed iterator of a sequence.
Syntax
reversed(sequence)
reversed() Parameters
Python reversed()
function parameters:
Parameter | Condition | Description |
---|---|---|
sequence | Required | The sequence object (list, string, tuple, range, etc.) to be reversed. |
Set and Dictionary are not considered sequence objects!
reversed() Return Value
Python reversed()
function returns an iterator that yields the elements of the sequence in reverse order.
Examples
Example 1: Reversing a String
Let's iterate over a string in reverse order: first use reversed()
function to get an iterator and then use it in a for loop:
greeting = "Hello World!"
for char in reversed(greeting):
print(char, end="")
output
!dlroW olleH
Example 2: Reversing a List
You can iterate over a list in reverse order, for example:
numbers = [1, 2, 3, 4, 5]
for num in reversed(numbers):
print(num)
output
5
4
3
2
1
Example 3: Reversing a Tuple
In the same way, you can iterate in reverse order over elements of a tuple:
my_tuple = ('apple', 'banana', 'cherry')
for item in reversed(my_tuple):
print(item)
output
cherry
banana
apple
Example 4: Reversing a Range
reversed()
function can be used also with ranges:
for i in reversed(range(1, 5)):
print(i)
output
4
3
2
1
Example 5: Using reversed() with Custom Objects
To use reversed()
with custom objects, you need to implement the __reversed__()
method within your class. This method should return an iterator that yields the elements of the object in reverse order.
class Vowels:
vowels = ['a', 'e', 'i', 'o', 'u']
def __reversed__(self):
return reversed(self.vowels)
v = Vowels()
# reverse a custom object v
print(list(reversed(v))) # Output: ['u', 'o', 'i', 'e', 'a'
output
['u', 'o', 'i', 'e', 'a']