The reversed()
function is a built-in function in Python that returns a reverse iterator for a sequence. It takes a sequence as an argument and returns an iterator that traverses the elements in the sequence in reverse order.
Parameter Values
Parameter | Description |
---|---|
sequence | A |
Return Values
reversed()
returns an iterator that accesses the given sequence in reverse.
How to Use reversed()
in Python
Example 1:
The reversed()
function returns an iterator that iterates over the elements of a sequence in reverse order.
nums = [1, 2, 3, 4, 5]
reversed_nums = reversed(nums)
for num in reversed_nums:
print(num)
Example 2:
The reversed()
function works with strings as well, iterating over characters in reverse order.
word = 'hello'
reversed_word = ''.join(reversed(word))
print(reversed_word)
Example 3:
The reversed()
function can be used with custom classes that define the __reversed__ method to customize the reverse iteration behavior.
class CustomList:
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, index):
return self.data[index]
def __reversed__(self):
return reversed(self.data)
custom_list = CustomList([1, 2, 3, 4, 5])
for num in reversed(custom_list):
print(num)