Python Fundamentals ยท Collections

Sets: Unique Items

Sets keep each value once. Remove duplicates in one step and compare groups with &, | and -.

sets.py

rolls = [3, 1, 3, 6, 1, 3]
seen = set(rolls)           # duplicates disappear
seen.add(4)
seen.add(3)                 # already there: nothing changes
evens = {2, 4, 6}
both = seen & evens         # in both sets
either = seen | evens       # in at least one
only_seen = seen - evens    # in seen but not in evens
print(seen, both, either, only_seen, 6 in seen)

Step by step

  1. rolls is created and points to a new list: [3, 1, 3, 6, 1, 3].
  2. set() keeps one of each value: {1, 3, 6}. The duplicates are gone.
  3. In the set that seen points to, index 2 changes from 6 to 4 and index 3 changes from null to 6.
  4. Adding 3 again changes nothing: it is already there.
  5. evens is created and points to a new set: [2, 4, 6].
  6. & keeps what is in both sets: {4, 6}.
  7. | combines both sets: {1, 2, 3, 4, 6}.
  8. - keeps what is in seen but not in evens: {1, 3}.
  9. Sets answer "which unique values?" and "what do these groups share?" in one operator each.