A log contains repeated user names with inconsistent letter case.
What You Need to Understand
A set comprehension builds a set by evaluating an expression for each source element, optionally filtering with if. Duplicates disappear automatically.
When to Use It
A log contains repeated user names with inconsistent letter case.
Step-by-Step Python Example
names = ["MAYA", "Maya", "noa", "NOA"]
normalized_names = {name.casefold() for name in names}
print(sorted(normalized_names))
How the Example Works
Each name is case-folded before being stored in a set, resulting in two distinct normalized names.
Example Output
['maya', 'noa']
{1, 4, 9, 16, 25}
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
print({number * number for number in range(1, 6)})
Important Behavior and Edge Cases
Set comprehensions do not preserve source order. If you need an ordered unique list, use dict.fromkeys() or an explicit seen-set strategy.
Try It Yourself
Create a set of squares for integers 1 through 5.
Common Beginner Mistakes
- Set comprehensions do not preserve source order. If you need an ordered unique list, use
dict.fromkeys()or an explicit seen-set strategy. - Depending on set iteration order or using a set when duplicates and original positions must be preserved.
Key Takeaways
- A set comprehension builds a set by evaluating an expression for each source element, optionally filtering with
if. - Each name is case-folded before being stored in a set, resulting in two distinct normalized names.
- Set comprehensions do not preserve source order.