Python 3D Academyবাংলা

Making sets

🌍 In real life. A stamp collector keeps one of each stamp. If a friend gives them a stamp they already have, the collection doesn't grow. And nobody asks "what's the 3rd stamp?"; the only question that matters is "do you have this one?".

A set is Python's collection for exactly that: one of each, no order, and a very fast "do you have it?".

The idea in one sentence: a set holds each value only once, keeps no order, and answers in very quickly.

Its words:

  • set: values in curly braces, {3, 1, 2}
  • duplicate: a repeated value; a set keeps just one copy
  • set(...): makes a set from a list or a string; set() is an empty set
  • in / not in: is this value in the set?

Step by step, for nums = {3, 1, 3, 2, 1}:

  1. Python puts in 3, then 1.
  2. The next 3 is already there, so it's left out; 2 goes in; the last 1 is left out.
  3. nums holds 3 values, so len(nums) is 3.
nums = {3, 1, 3, 2, 1}
print(len(nums))
print(sorted(nums))
sorted() gives the set's values as a list, smallest first. Printing a set itself works too, but the order of its values can change from one run to the next.

set(...) turns a list (or a string) into a set, so it's a quick way to throw away repeats. An empty set is written set(), because {} makes an empty dictionary (Chapter 11).

names = ["Ana", "Bo", "Ana", "Cy", "Bo"]
unique = set(names)
print(len(unique))
print(sorted(unique))
print(len(set("banana")))

in asks whether a value is in the set. Sets are built for this question, so they answer it very fast, even when they are huge.

pets = {"cat", "dog", "fish"}
print("dog" in pets)
print("cow" in pets)
print("cow" not in pets)

How Python does it: why in is so fast. A set doesn't keep its values in a row. For each value, Python works out a number called its hash, and the hash says which slot the value belongs in, like a locker number worked out from your name. To answer "dog" in pets, Python works out the hash of "dog" and looks in that one slot. It doesn't walk through the other values.

What it costs. That makes in on a set about as fast for a million values as for three. On a list, in may check every item. The price: a set has no positions and no order, and it can only hold values that never change (numbers, strings, tuples), because a changed value would have a different hash.

A set has no order, so it has no positions either. pets[0] is an error:

pets = {"cat", "dog"}
print(pets[0])

Mistakes and edge cases.

  • An index. pets[0] gives TypeError: 'set' object is not subscriptable (above).
  • {} for an empty set. {} is an empty dictionary; write set().
  • A list inside a set. {[1, 2]} gives TypeError: cannot use 'list' as a set element (unhashable type: 'list'). Use a tuple, {(1, 2)}.
  • Printing a set and expecting an order. A set of strings can print in a different order on each run. Use sorted(...) when the order matters.

Quiz

  1. What does this print?

    print(len({1, 2, 2, 3, 3, 3}))
  2. What does this print?

    print(sorted({5, 1, 5, 3}))
  3. How do you make an empty set?

    • set()
    • {}
    • []
  4. What does this print?

    print(len(set("banana")))
  5. What does this print?

    s = {"a", "b"}
    print("c" in s)
  6. Which line has a mistake?

    colors = {"red", "blue"}
    print(colors[0])

Coding tasks

  1. Ask for some words on one line, separated by spaces. Print how many different words there are.

  2. Make a set called vowels with "a", "e", "i", "o" and "u". Ask for one lowercase letter and print vowel or consonant.

  3. Ask for whole numbers on one line, separated by spaces. Print each different number once, smallest first, on one line with a space after each.