Sets
A list can hold the same value many times. Sometimes you only want to know which values there are, each of them once: which kinds of pets the students in a class have, or who visited a website. For that, Python has sets. A set is written in curly braces, like a dictionary, but it holds single values instead of pairs:
pets = {"dog", "cat", "dog", "fish", "cat"}
print(pets)
print(len(pets)){'cat', 'fish', 'dog'}
3Each value is in a set only once, as each key is in a dictionary only once. The second "dog" and the second "cat" were left out, so len() counts the different values: 3.
And a set has no order. It doesn't remember the order in which you wrote the values, so it has no indexes either: pets[0] ends with TypeError: 'set' object is not subscriptable (it can't be read with square brackets). When you print a set of texts, the order can even change from one run to the next. The output above is from one run; another run printed {'fish', 'dog', 'cat'}.
Most often, you make a set from a list with set(). It's the quickest way to get rid of duplicates:
votes = ["zoo", "castle", "zoo", "aquapark", "zoo"]
places = set(votes)
print(len(votes), len(places))
print("castle" in places)
print("museum" in places)5 3
True
FalseFive votes, but only three different places. in works as it does with a list: it tells you whether a value is in the set.
Watch out for one trap: {} isn't an empty set, it's an empty dictionary. An empty set is written set(), and that's also how Python prints it.
Instructions
- 1
Make a set
usersfrom the listvisits, and print how many different users signed in:Users: 4. Keep the line with the list: the exercise also tries other visits. - 2
Below, check with
inwhether"lily"is among the users: printLily was here.if she is, andLily wasn't here.if she isn't.