Unravelling comprehensions

After failing to unravel generator expressions, in this post as part as my Python syntactic sugar post series I want to tackle comprehensions. Thanks to a change made in Python 3.0, recreating comprehensions using generator expressions is straightforward since comprehensions do not leak their loop variant.

List comprehensions

Unravelling [c for b in a] is list(c for b in a): take the body of the list comprehension and pass it to list() as a generator expression.

Set comprehensions

Unravelling {c for b in a} is set(c for b in a). I suspect you're starting to see a pattern...

Dict comprehensions

There's a slight trick to dict comprehensions in that the generator expression needs to return key/value pairs, otherwise it's the same "pass a generator to the type's constructor" trick. That means {c: d for b in a} becomes dict((c, d) for b in a).

Aside: why isn't there a tuple comprehension?

There are two reasons why there is no such thing as a "tuple comprehension".

One is how would you represent that syntactically? The obvious syntax of parentheses around a comprehension-like syntax, but that's taken by generator expressions.

The second reason is a "tuple comprehension" is a misuse of tuples. The data structure is meant to provide an index-based struct instead of an immutable sequence. Consider a pair of key and value like we did for  dict comprehensions: (key, value). What's represented by index 0 means something different than what is in index 1.

Brett Cannon

Brett Cannon

Vancouver, BC, Canada