12.8 Set Methods
Method equivalents of union/intersection/difference/symmetric_difference, plus the relationship-testing methods with no operator form -- issubset(), issuperset(), isdisjoint() -- and copy()'s shallow copy.
Method equivalents of the operators in 12.7 Set Operators, plus relationship-testing methods that have no operator form.
union()
Same as | — method form is useful when chaining or passing as a function argument.
>>> {1, 2, 3}.union({2, 3, 4})
{1, 2, 3, 4}
intersection()
>>> {1, 2, 3}.intersection({2, 3, 4})
{2, 3}
difference()
>>> {1, 2, 3}.difference({2, 3, 4})
{1}
symmetric_difference()
>>> {1, 2, 3}.symmetric_difference({2, 3, 4})
{1, 4}
issubset()
True if every element of this set is also in the other set.
>>> {1, 2}.issubset({1, 2, 3})
True
issuperset()
True if this set contains every element of the other set — the inverse relationship of issubset().
>>> {1, 2, 3}.issuperset({1, 2})
True
isdisjoint()
True if the two sets share no elements at all.
>>> {1, 2}.isdisjoint({3, 4})
True
copy()
Returns a shallow copy — a new set object with the same elements.
>>> a = {1, 2, 3}
>>> c = a.copy()
>>> c is a, c == a
(False, True)
Quick Interview Answer
“Every operator from the previous section has a method twin —
union(),intersection(),difference(),symmetric_difference()— useful mainly when chaining or passing as a function argument, where an operator can’t be used directly. The methods with no operator equivalent are the relationship tests:issubset()andissuperset()are inverses of each other, andisdisjoint()checks for zero overlap.copy()returns a genuine shallow copy — unlike a tuple’scopy.copy(), which can return the identical object since tuples are immutable, a set’scopy()always produces a distinct object, since a set is mutable and the copy must be safe to modify independently.”
Common Mistakes
- Confusing
issubset()andissuperset()—a.issubset(b)asks “is everything inaalso inb?”;a.issuperset(b)asks the reverse. - Using
a.difference(b)and expecting it to also remove those elements froma— it returns a new set; usedifference_update()if in-place removal is actually wanted. - Assuming
copy()performs a deep copy — like any shallow copy, if the set held mutable objects (which it normally can’t, since elements must be hashable) only the top-level container would be duplicated.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form