A comprehension is a fancy way of saying: "a more compact way of looping over, as well as filtering, a collection and generating a new collection from that process".
There are three types of 'comprehensions' in Python to align with the various 'collection' types:
- List
- Dict
- Set
They all work the same but differ in the type that is generated at the end.
The syntax structure for each type looks like this:
# List
(values) = [ (expression) for (item) in (collection) if condition ]
# Dict/Set
(values) = { (expression) for (item) in (collection) if condition }
Note: yes the Dict and Set syntax structure is the same but the output type will be different (as we'll see in the following examples) because the Dict will output key/value pairs, while the Set will output individual element values.
Here are examples of each...
# List Output:
# [0, 4, 16, 36, 64]
[x * x for x in range(10) if x % 2 == 0]
# Set Output
# {0, 4, 16, 36, 64}
{x * x for x in range(10) if x % 2 == 0}
# Dict Output
# {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
{x: x * x for x in range(10) if x % 2 == 0}
Note: I've used the full syntax structure, but you don't have to. You could just use
for (item) in (collection)
and not include theif condition
part.
If we were to write this code without comprehensions, then it would look like the following (yes it is a lot more verbose, but ultimately just a multi-lined version):
# List
output = []
for x in range(10):
if x % 2 == 0:
output.append(x * x)
# Set
output = set()
for x in range(10):
if x % 2 == 0:
output.add(x * x)
# Dict
output = dict()
for x in range(10):
if x % 2 == 0:
output.update({x: x * x})