Python 3D Academyবাংলা

Changing a set

🌍 In real life. At a club's door, a guard keeps a list of who's inside. When someone arrives, their name is added, unless it's already there. When someone leaves, their name is crossed out. And if the guard is asked to cross out a name that was never there, they can either complain loudly or just shrug.

A set changes the same way, and Python gives you both kinds of guard.

The idea in one sentence: add puts a value in (if it isn't there already), remove takes it out and complains if it's missing, and discard takes it out quietly.

Its words:

  • s.add(x): put x in; adding a value that's already there changes nothing
  • s.remove(x): take x out; a missing x stops the program with a KeyError
  • s.discard(x): take x out; a missing x is ignored
  • seen: the usual name for a set of things you've already met

Step by step, for the set below:

  1. s starts as {1, 2}. add(2): already there, no change.
  2. add(5): now {1, 2, 5}.
  3. discard(9): 9 isn't there, so nothing happens, and no error.
  4. remove(1): 1 is there, so it's taken out: {2, 5}.
s = {1, 2}
s.add(2)
s.add(5)
s.discard(9)
s.remove(1)
print(sorted(s))
s = {1}
s.remove(7)

A very handy pattern: start with an empty set called seen, and add each thing as you meet it. Then in seen tells you whether you've met it before.

seen = set()
for n in [4, 7, 4, 2, 7]:
    if n in seen:
        print(n, "again!")
    else:
        seen.add(n)

What it costs. add, remove, discard and in each look in just one slot (by the value's hash), so each is about equally fast whether the set holds ten values or a million. That's why the seen pattern is so good: checking "have I met this before?" stays quick however many things you've met. With a list instead of a set, every check would walk the whole list.

Mistakes and edge cases.

  • remove() of a missing value. s.remove(7) gives KeyError: 7. Use discard when "not there" is fine.
  • Expecting add() to count. Adding the same value twice still leaves one copy; use a dictionary (Chapter 11) to count.
  • Adding a list. s.add([1]) gives TypeError: cannot use 'list' as a set element (unhashable type: 'list').
  • Keeping what add() gives back. Like list methods that change things, add gives back None.

Quiz

  1. What does this print?

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

    s = {1, 2, 3}
    s.discard(5)
    s.discard(1)
    print(sorted(s))
  3. Which one stops with an error when the value isn't in the set?

    • remove()
    • discard()
    • add()
  4. What does this print?

    seen = set()
    for ch in "hello":
        seen.add(ch)
    print(len(seen))
  5. Which line has a mistake?

    s = set()
    s.append(1)
    print(len(s))

Coding tasks

  1. Start with guests = {"Ana", "Bo"}. Add "Cy", remove "Ana", then print sorted(guests).

  2. Ask for some words on one line. Print the first word that appears for a second time, or none if no word repeats.

  3. Ask for whole numbers on one line. Print True if any number appears more than once, otherwise False.