Adding to a Set
A set can change: you can add values to it and remove them. The method .add() adds a value. When the value is already there, nothing happens, so the set never holds it twice:
badges = set()
badges.add("first win")
badges.add("10 games")
badges.add("first win")
print(len(badges))2Start with set(), not with {}. {} is an empty dictionary, and a dictionary has no .add(): the program would end with AttributeError: 'dict' object has no attribute 'add'.
Thanks to .add(), a set is great for collecting values that should be there only once. Go through a list in a loop and add each value to the set: whatever repeats is left out on its own. Together with what you know about text, you can count the different words in a sentence, whatever their case:
sentence = "The cat and the dog and THE bird"
words = set()
for word in sentence.split():
words.add(word.lower())
print(len(words))5The sentence has 8 words, but only 5 different ones once they are all in lowercase: the, cat, and, dog and bird.
There are two methods for removing a value:
.discard()removes the value if it's in the set, and does nothing if it isn't..remove()removes it too, but when the value isn't in the set, the program ends with an error, as it does with.remove()of a list. With a set, it's aKeyError:words.remove("fish")ends withKeyError: 'fish'.
So use .discard() when it doesn't matter whether the value was there.
Instructions
- 1
Create an empty set
guests. Then go throughentriesin a loop and add each name to the set cleaned up: without the spaces around it, and in lowercase. Print how many different guests there were:Guests: 4. Keep the line with the list: the exercise also tries other entries. - 2
Max only tried out the pen; he wasn't a guest. Below, remove
"max"from the set with.discard()and print the number of guests again:Guests: 3. With.discard(), the program works even on a day when Max didn't write anything.