Skip to content
thesarfo

Reference

Set Operations & Methods (Python)

Python set membership operators and the core set methods for union, intersection, and difference.

views 0

A set is an unordered collection of zero or more immutable Python data objects.

>>> {3, 6, "cat", False}

Operations on a Set

  1. Membershipin — set membership.
  2. Lengthlen — returns the cardinality of the set.
  3. |aset | otherset — returns a new set with all elements from both sets.
  4. &aset & otherset — returns a new set with only the elements common to both sets.
  5. -aset - otherset — returns a new set with all items from the first set not in the second.
  6. <=aset <= otherset — asks whether all elements of the first set are in the second.

Set Methods

  1. unionaset.union(otherset) — returns a new set with all elements from both sets.
  2. intersectionaset.intersection(otherset) — returns a new set with only the elements common to both sets.
  3. differenceaset.difference(otherset) — returns a new set with all items from the first set not in the second.
  4. issubsetaset.issubset(otherset) — asks whether all elements of one set are in the other.
  5. addaset.add(item) — adds item to the set.
  6. removeaset.remove(item) — removes item from the set.
  7. popaset.pop() — removes an arbitrary element from the set.
  8. clearaset.clear() — removes all elements from the set.