Advanced Set Operations
Set operations describe how two collections relate to each other.
Try it: Sets: Unique Members and Venn Operations
How a Python set keeps each value once, answers membership, and combines two sets by membership alone: union, intersection, difference and symmetric difference.
How it works
- set(list) adds each value; a value already in the set changes nothing.
- x in s asks only whether the value is present (no position, no count).
- Every member is only in A, only in B, or in both.
- A | B keeps all, A & B the shared ones, A - B those only in A, A ^ B those in exactly one.
- A set has no order of its own, so the lab shows members sorted, as sorted(s) would.
Default run (16 steps): Build two sets from lists. Sets keep no order, so members are drawn sorted here (like sorted(s)); Python's own print order may differ. … sorted(A & B) → ['india', 'peru'] (2 members; sorted only for display).
Simplified: Up to 8 short words or ints per set; the members are displayed sorted because Python's set iteration order depends on hashing and is not meaningful.
Loading the simulation…
Why Sets Matter
A set is an unordered collection of unique elements. It is useful when the important question is whether an item belongs to a collection, rather than where the item appears or how many times it occurs. This makes sets different from lists, which preserve order and allow duplicates.
Set Contents
You can create a set with set() by passing it a list or another iterable. You can also create a set with curly braces when the set contains elements directly. During creation, Python removes duplicate values automatically. The resulting set contains each distinct value once, and the order in which values were supplied does not define an order inside the set.
| Property | List | Set |
|---|---|---|
| Order | Preserves order | Unordered |
| Duplicates | Allows duplicates | Keeps each value only once |
| Typical priority | Order or frequency | Membership or uniqueness |
| Indexing | Supports positions | Does not support indexing |
The collection type should match what your program needs to preserve.
Membership Changes
After creating a set, use the in operator to test whether an element belongs to it. Use add() to insert an element and remove() to delete an element. Adding an element that is already present does not create a duplicate: the set remains the same size and no error is raised.
Tracking country membership
Start with bri containing brazil, india, and russia. Test two membership questions, make an independent copy called bric, add china to bric, and remove russia from bri.
- 1Test membership
india belongs to bri, while usa does not belong to bri.
- 2Copy before changing
Create bric as a copy of bri so it can be modified independently.
- 3Add an element
Add china to bric. The resulting bric contains all elements of bri plus china, so bric is a superset of bri.
- 4Remove an element
Remove russia from bri. The remaining elements are brazil and india.
bri contains brazil and india after removal. bric contains brazil, russia, india, and china after the addition.
Relationships Between Sets
Set operations describe how two collections relate to each other. The intersection contains only elements that appear in both sets. The union combines the elements from both sets while retaining uniqueness. The difference contains elements found in one set and not in the other. These operations are useful when comparing collections by membership rather than by position.
| Operation | Meaning | Result for bri and bric |
|---|---|---|
| Intersection | Elements in both sets | brazil and india |
| Union | Elements in either set, with duplicates removed | brazil, india, russia, and china |
| Difference | Elements in the first set that are not in the second | No elements from bri beyond bric |
Set relationships are based on membership, not element positions.
Use the intersection when you need the overlap between collections, the union when you need one combined collection of unique elements, and the difference when you need to identify what one collection has that another does not.
Common Set Mistakes
Common mistake Expecting duplicate additions to increase the set size
What it looks likeAdding brazil to a set that already contains brazil
Why it failsSets enforce uniqueness automatically.
Do this insteadTreat the repeated addition as having no effect on the set's contents.
Common mistake Expecting a set to preserve the input order
What it looks likeAssuming the first supplied value will be at position zero
Why it failsSets are unordered and do not support indexing.
Do this insteadUse a list when the order or position of values matters.
Common mistake Using a list when only membership matters
What it looks likeKeeping repeated values when the collection should contain each value only once
Why it failsLists allow duplicates and are designed to preserve order.
Do this insteadChoose a set when uniqueness and membership are the priorities.
Common mistake Confusing intersection with union
What it looks likeExpecting the intersection of bri and bric to include china
Why it failsAn intersection contains only values present in both sets.
Do this insteadUse the union when you need values from either set; use the intersection for shared values.
Practice Check
A collection must contain the unique names found across two groups. The order of the names is irrelevant, repeated names should appear only once, and you also need to identify the names shared by both groups. Which collection type and which set operations would you choose?
Hints
- The requirement for unique values points toward a set.
- The combined collection uses union.
- The shared names use intersection.
What do you think happens?
Predict what happens when an element already in a set is added again.
Reveal answer
The set remains unchanged
Sets automatically enforce uniqueness, so adding an element that is already present does not change the set and does not raise an error.
Key Takeaways
- 1Sets are unordered collections of unique elements.
- 2Use sets when membership and uniqueness matter more than order or frequency.
- 3Use in to test membership,
add()to insert an element, andremove()to delete an element. - 4Intersection finds shared elements, union combines unique elements, and difference finds elements present in one set but not another.
- 5Use lists when you need order, positions, or duplicate values.
At a glance
- Sets represent unique membership without preserving order.
- Duplicate values are automatically removed, and adding an existing value changes nothing.
- Membership tests, additions, and removals let you inspect and update a set.
- Intersection, union, and difference reveal relationships between collections.
- Lists are preferable when order or duplicate values must be retained.