Skip to content

Sets and membership [ref]

Problem

  • Create an empty set and add 3.
  • Test membership of 3 and nonmembership of 2 in {1, 3, 5}.
  • Deduplicate [1, 2, 2, 3].
  • Find the intersection and difference of {1, 2, 3} and {2, 4}.
  • Remove 2 from {1, 2}, then discard missing 9 without an error.
  • Build a set of lengths from ["a", "to", "tea"].
  • Try to put [1, 2] in a set, then put (1, 2) in one instead.

Python solution

seen = set()
seen.add(3)
seen  # {3}

3 in {1, 3, 5}      # True
2 not in {1, 3, 5}  # True

set([1, 2, 2, 3])  # {1, 2, 3}

a, b = {1, 2, 3}, {2, 4}
a & b  # {2}
a - b  # {1, 3}

values = {1, 2}
values.remove(2)
values.discard(9)
values  # {1}

{len(word) for word in ["a", "to", "tea"]}  # {1, 2, 3}

try:
    {[1, 2]}
except TypeError:
    unhashable = True
unhashable  # True
{(1, 2)}    # {(1, 2)}