Skip to content

Sets

Build a set to drop duplicates and test membership, combine two sets with union, intersection and difference, and say why a set membership test is fast.

It opens on

ids = [3, 1, 3, 2, 1] has five entries with repeats. After s = set(ids), how many items does s hold: 5, 3 or 2?

Why it matters

Removing repeats, asking whether a value was seen before and comparing two groups, who is in both classes, who is in only one, are everyday jobs, and a set does each in a line and finds a value much faster than a long list does.

Good to know first

  • Lists: indexing and mutation: a list may hold repeats and is read by index
  • Dictionaries: keys are unique and must be hashable, and {} makes an empty dictionary
  • for loops over a list visit each item in turn

Step by step

  1. A set keeps each value once

    Build a set from a list, say how many items it holds, test membership and add to it, and write an empty set.

    Each value of ids goes in once, and a repeat does nothing. So s holds 3, 1 and 2, the run printed the set {1, 2, 3} and the lengths 5 and 3. That answers the opening question.

    what the run printed

    A common mix-up

    A set keeps its repeats, in the order given, like a list.

    In fact: It keeps each value once and promises no order.

  2. Two rosters

    Compute the union, intersection and difference of two sets, and say who is in each result.

    Math has four students and cs has three, but the union printed five names, Ana, Bo, Cy, Di and Ed, because Bo and Di are counted once.

    A common mix-up

    The union adds the sizes, so it holds 4 + 3 students.

    In fact: a student in both is stored once, so its size is 4 + 3 minus the 2 shared, which is 5.

  3. Fast membership and the seen set

    Use a set called seen to find repeated words in one pass, and say why a set membership test is faster than a list's.

    For the first word, to, the test to in seen is False, so nothing is printed, and add puts to in. The words be, or and not are new in the same way.

    A common mix-up

    A set test and a list test cost the same.

    In fact: a list test may look at every item, up to n, while a set test takes about one check on average.

Try it

What does len(set([4, 4, 7, 7, 7, 2])) give?Answer

3

Hint: The different values are 4, 7 and 2

With a = {"x", "y", "z"} and b = {"y", "w"}, what are a & b and a - b?Answer

{"y"} and {"x", "z"}

Hint: Only y is in both

For words = ["a", "b", "a", "a"], how many repeats does the same loop print?Answer

2

Hint: The second and third a

How many different words does len(set(["to", "be", "or", "not", "to", "be"])) count?Answer

4, the words to, be, or and not.

The difference math - cs is everyone in math who is not in cs. Who is that?Answer

Ana and Cy.

Sets

30 minutes every month. No card.