🐍

Sets in Python

Programare Python Intermediate 5 min read

Sets in Python

Creating Sets

s = {1, 2, 3}
s = set([1, 2, 2, 3])  # {1, 2, 3} - removes duplicates
empty = set()          # NOT {} (that's empty dict!)

Properties

  • Unordered - no indexing
  • Unique elements only
  • Elements must be hashable

Adding/Removing

  • add(x) - Add single element
  • update(iterable) - Add multiple
  • remove(x) - Remove (KeyError if missing)
  • discard(x) - Remove (no error if missing)
  • pop() - Remove and return arbitrary element

Set Operations

a | b    # Union
a & b    # Intersection
a - b    # Difference
a ^ b    # Symmetric difference

Comparisons

  • a <= b or a.issubset(b) - Subset
  • a >= b or a.issuperset(b) - Superset
  • a.isdisjoint(b) - No common elements

Frozenset

Immutable set, can be dict key:

fs = frozenset([1, 2, 3])

Key Points

  • {} creates dict, not set! Use set()
  • Elements must be hashable
  • remove() raises error, discard() doesn’t
  • Operators: | union, & intersection, - difference

📚 Related Articles