An event list is sorted by priority without losing chronological order among equal-priority entries.
What You Need to Understand
Python sorting is stable: records with equal sort keys retain their original relative order. This lets you use a sequence of sorts or add a tie-breaker key explicitly.
When to Use It
An event list is sorted by priority without losing chronological order among equal-priority entries.
Step-by-Step Python Example
events = [("first", 2), ("second", 1), ("third", 2)]
ordered = sorted(events, key=lambda event: event[1])
print(ordered)
How the Example Works
The priority-1 event comes first, while first stays before third because their priorities are equal.
Example Output
[('second', 1), ('first', 2), ('third', 2)]
['Ann', 'Bob', 'Liam']
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
names = ["Ann", "Bob", "Liam"]
print(sorted(names, key=len))
Important Behavior and Edge Cases
Never rely on arbitrary input order if a reproducible secondary sort key is needed; specify it rather than assuming a different iteration order.
Try It Yourself
Sort a list of names by length and check the relative order of equally long names.
Common Beginner Mistakes
- Never rely on arbitrary input order if a reproducible secondary sort key is needed; specify it rather than assuming a different iteration order.
- Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
- Python sorting is stable: records with equal sort keys retain their original relative order.
- The priority-1 event comes first, while
firststays beforethirdbecause their priorities are equal. - Never rely on arbitrary input order if a reproducible secondary sort key is needed; specify it rather than assuming a different iteration order.