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.

Python reversed icon

✅ 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

Popular posts from this blog

Mastering Python Generators and yield: Efficient Iteration Explained

Mastering Python Sets: Remove Duplicates and Do More

Python Logging Module: Basics and Best Practices ๐Ÿ“