Comprehensions

Comprehensions#

Python supports a concise notation called comprehensions for writing down for loops that generate data structures—you can think of it as a way of automatically combining map and filter.

Here’s a list comprehension:

You can use comprehensions with dictionaries and sets (which we haven’t looked at). Here’s an example with dictionaries:

And here’s one with sets (which are unordered groupings of unique elements, i.e. dictionaries with keys but no values):

You can put conditionals in a comprehension to get filtering:

You can read more about comprehensions in the Python data structure documentation.