Comprehensions

Comprehensions

Constructs that allow sequences to be built from other sequences.

Several types of comprehensions are supported:

  • list comprehensions

  • dictionary comprehensions

  • set comprehensions

  • generator comprehensions

list comprehensions

Short way to create lists.

Square brackets

Blueprint

variable = [out_exp for out_exp in input_list if out_exp == 2]

Example:

multiples = [i for i in range(30) if i % 3 == 0]
print(multiples)
# Output: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27] 

Example with for loop:

Example with list comprehensions:

dict comprehensions

Short way to create dicts

Curly braces {}

Example:

In the above example we are combining the values of keys which are same but in different typecase.

Example: switch keys and values of a dictionary:

set comprehensions

Short way to create sets

Curly braces {}.

Example:

generator comprehensions

They don’t allocate memory for the whole list but generate one item at a time.

More memory efficient.

Example:

Last updated