The reversed() function in Python is a built-in function used to return an iterator that accesses the elements of a sequence in reverse order. It does not modify the original sequence; instead, it produces a reverse iterator that allows elements to be retrieved from the last element to the first.
The reversed() function works with sequence types such as lists, tuples, strings, and ranges.
reversed(sequence)
Parameter
Return Value
numbers = [1, 2, 3, 4, 5]
rev = reversed(numbers)
print(list(rev))
Output
[5, 4, 3, 2, 1]
Explanation
reversed(numbers) creates a reverse iterator.list() shows the elements in reverse order.reversed() in a Loopnumbers = [10, 20, 30, 40]
for num in reversed(numbers):
print(num)
Output
40
30
20
10
Explanation
text = "Python"
for char in reversed(text):
print(char)
Output
n
o
h
t
y
P
Explanation
data = (1, 2, 3)
print(list(reversed(data)))
Output
[3, 2, 1]
Explanation
range()for i in reversed(range(5)):
print(i)
Output
4
3
2
1
0
Explanation
range(5) are accessed in reverse order.reversed() and SlicingUsing reversed()
numbers = [1, 2, 3, 4]
print(list(reversed(numbers)))
Using slicing
numbers = [1, 2, 3, 4]
print(numbers[::-1])
| Feature | reversed() | Slicing |
|---|---|---|
| Return type | Iterator | List |
| Memory usage | More efficient | Creates a new list |
| Usage | Iteration | Direct reversed copy |
reversed() is a built-in Python function used to iterate through a sequence in reverse order.