Iterate Backward with Python's reversed() Function
Iterate Backward with Python's reversed() Function ๐
Python’s reversed() function allows you to loop over a sequence in reverse order.
Unlike slicing, it does not modify the original list and is memory-efficient.
✅ Basic usage
# Basic reversed() usage
numbers = [1, 2, 3, 4, 5]
for n in reversed(numbers):
print(n)
✅ reversed() returns an iterator
# reversed() returns an iterator
rev = reversed(numbers)
print(list(rev)) # [5, 4, 3, 2, 1]
✅ Compared with slicing
# Compare with slicing
print(numbers[::-1]) # [5, 4, 3, 2, 1]
✅ The original list is untouched
# Original list remains unchanged
print(numbers) # [1, 2, 3, 4, 5]
reversed() is perfect when you need to iterate backwards without copying or modifying the list.
It communicates intent clearly and improves code readability.
Reverse smart, not hard.
reversed() is your go-to for backward iteration with clarity and efficiency. ๐
Icons by Flaticon
Comments
Post a Comment