A conference combines several registration lists.
What You Need to Understand
set.union(*others) returns a new set containing unique members from the original set and all provided iterables. The original remains unchanged.
When to Use It
A conference combines several registration lists.
Step-by-Step Python Example
morning = {"Maya", "Noa"}
afternoon = {"Noa", "Avi"}
all_names = morning.union(afternoon)
print(sorted(all_names))
print(sorted(morning))
How the Example Works
The union has three names and duplicates disappear. The morning set remains unchanged.
Example Output
['Avi', 'Maya', 'Noa']
['Maya', 'Noa']
[1, 2, 3, 4]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
print(sorted({1}.union([2, 3], (3, 4))))
Important Behavior and Edge Cases
union() accepts several iterable arguments, unlike some set operators that require sets. It does not preserve order.
Try It Yourself
Combine three groups of IDs into one unique set.
Common Beginner Mistakes
union()accepts several iterable arguments, unlike some set operators that require sets. It does not preserve order.- Using the wrong collection method for this operation without checking whether it mutates the object, returns a result, or raises on missing data.
Key Takeaways
set.union(*others)returns a new set containing unique members from the original set and all provided iterables.- The union has three names and duplicates disappear.
union()accepts several iterable arguments, unlike some set operators that require sets.