A timeline displays recent events before older ones.
What You Need to Understand
reversed(sequence) returns an iterator that walks a reversible sequence backward without modifying it. Convert the iterator to a list when a concrete collection is required.
When to Use It
A timeline displays recent events before older ones.
Step-by-Step Python Example
events = ["opened", "edited", "saved"]
for event in reversed(events):
print(event)
print(events)
How the Example Works
The loop visits saved, edited and opened in that order; the original list order remains unchanged.
Example Output
saved
edited
opened
['opened', 'edited', 'saved']
[3, 2, 1]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
numbers = [1, 2, 3]
print(list(reversed(numbers)))
Important Behavior and Edge Cases
Not every iterable supports reversed() directly. list.reverse() modifies a list in place, while slicing with [::-1] creates a copy.
Try It Yourself
Print an event list backward and then forward.
Common Beginner Mistakes
- Not every iterable supports
reversed()directly.list.reverse()modifies a list in place, while slicing with[::-1]creates a copy. - Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
reversed(sequence)returns an iterator that walks a reversible sequence backward without modifying it.- The loop visits
saved,editedandopenedin that order; the original list order remains unchanged. - Not every iterable supports
reversed()directly.