Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

List & Dict Comprehensions in Python



David Egan

Python comprehensions are syntactic sugar constructs that provide a way to build a list, dictionary or set from a starting list, dictionary or set whilst altering or filtering elements.

Comprehensions follow mathematical set builder notation rather than map and filter functions.

List Comprehension

Make a List that contains the doubled values of a starting list:

values = [2, 4, 6, 8, 10]
doubled_values = [x*2 for x in values]
print(doubled_values) # Outputs [4, 8, 12, 16, 20]

You could achieve the same result like this:

values = [2, 4, 6, 8, 10]
doubled_values = []
for x in values:
    doubled_values.append(x*2)
print(doubled_values)

…which is considerably more verbose.

List comprehensions have the same effect as the map method in other languages. For example, in JavaScript you could achieve the above like this:

const values = [2, 4, 6, 8, 10]
const doubled_values = values.map((x) => x*2)
console.log(doubled_values) // Outputs [ 4, 8, 12, 16, 20 ]

Filtering

You can filter a list by adding a conditional statement. A filtered list comprehension takes this form:

[ element-expression for element in sequence if boolean-expression ]

For example:

values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_values = [x for x in values if x %2 ==0]
odd_values = [x for x in values if x %2 !=0]
print(even_values)
print(odd_values)

# Make a list of the cubes of all even numbers
cubed_even_values = [x**3 for x in values if x %2 ==0]

References


comments powered by Disqus