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
list
comprehensionsShort way to create lists.
Square brackets
Blueprint
Example:
Example with for loop:
Example with list comprehensions:
dict
comprehensions
dict
comprehensionsShort 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
set
comprehensionsShort way to create sets
Curly braces {}
.
Example:
generator
comprehensions
generator
comprehensionsThey don’t allocate memory for the whole list but generate one item at a time.
More memory efficient.
Example:
Last updated