Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
[Python Comprehensions] #python3 #comprehensions


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:

  1. List
  2. Dict
  3. 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 the if 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})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.