Sets and set comprehensions
Sometimes you only care which values there are, not how many times each one comes up. A set is a collection for that. Each value is in a set only once, and a set keeps no order. You write one in curly brackets, or make one out of a list with set, which drops the repeats:
>>> colors = {"red", "blue", "red"}
>>> len(colors)
2
>>> "blue" in colors
True
>>> colors.add("green")
>>> colors.add("red")
>>> len(colors)
3
>>> set([3, 1, 3, 2, 1])
{1, 2, 3}The method add adds a value to a set, and adding a value that's already there changes nothing. An empty set is set(), because {} is an empty dictionary.
Sort a set before you print it
A set has no order of its own. Small whole numbers usually come out in increasing order, but strings come out in a different order from one run of the program to the next. So whenever you print a set of strings, or go through one, sort it first. sorted gives a sorted list:
>>> sorted({"pear", "apple", "fig"})
['apple', 'fig', 'pear']Set comprehensions
Curly brackets without a key and a colon make a set comprehension. The repeats disappear on their own:
words = ["tree", "car", "house", "dog", "bike", "sun"]
lengths = {len(word) for word in words}
print(lengths)
print(len(lengths), "different lengths")
{3, 4, 5}
3 different lengthsSix words, but only three different lengths. Here the set holds strings, so it's sorted before it's printed:
words = ["tree", "car", "house", "dog", "bike", "cat"]
first_letters = sorted({word[0] for word in words})
print(first_letters)
['b', 'c', 'd', 'h', 't']So curly brackets make two kinds of comprehension: with key: value a dictionary, and with a single expression a set.
A set has no indexes
Since a set keeps no order, there's no first or second item, and indexing stops the program:
lengths = {3, 4, 5}
print(lengths[0])
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(lengths[0])
~~~~~~~^^^
TypeError: 'set' object is not subscriptable"Subscriptable" means that something can be indexed with square brackets. To get the values in order, make a sorted list first: sorted(lengths)[0] is the smallest.