A course records attendance in arrival order and checks whether a student attended.
What You Need to Understand
Use lists for sequences where order, duplicates or indexing matter. Use sets for uniqueness and average constant-time membership tests on hashable items.
When to Use It
A course records attendance in arrival order and checks whether a student attended.
Step-by-Step Python Example
arrival_order = ["maya", "noa", "maya"]
attended = set(arrival_order)
print(arrival_order)
print("maya" in attended)
print(len(attended))
How the Example Works
The list keeps all three arrivals; the set stores only two unique names.
Example Output
['maya', 'noa', 'maya']
True
2
['a', 'b']
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
names = ["a", "b", "a"]
unique = list(dict.fromkeys(names))
print(unique)
Important Behavior and Edge Cases
Sets are not replacements for ordered logs, and their printed order is unpredictable. Use a list and companion set when you need both properties.
Try It Yourself
Track first visits in a list while using a set to avoid duplicates.
Common Beginner Mistakes
- Sets are not replacements for ordered logs, and their printed order is unpredictable. Use a list and companion set when you need both properties.
- Depending on set iteration order or using a set when duplicates and original positions must be preserved.
Key Takeaways
- Use lists for sequences where order, duplicates or indexing matter.
- The list keeps all three arrivals; the set stores only two unique names.
- Sets are not replacements for ordered logs, and their printed order is unpredictable.