Imagine a Python programmer. With a list of pairs of values to hand, they can always get a set of unique pairs by applying set()
. It's easy to get a dictionary from this set by applying the dict()
function. It seems that with list generators, we can describe dictionaries and sets as declarative, like lists.
However, this isn't an optimal solution in most cases: the entire intermediate list will be created and stored in memory. It'll be annoying to waste extra memory if there are many repeated values or keys when generating elements of a set or dictionary.
Python comes to our rescue — set generators and dictionary generators, which we'll look at in this lesson.
Set generators
With these generators, everything is super simple. It only takes two actions:
- Take the expression that defines the list generator
- Replace the square brackets with curly brackets
Let's see how it works:
squares = {x * x for x in range(10)}
squares
# {0, 1, 64, 4, 36, 9, 16, 49, 81, 25}
5 * 5 in squares
# True