Dev Notes

Software Development Resources by David Egan.

List & Dict Comprehensions in Python


Data Structures, 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]

Flatten a Multi-Dimensional List

To convert a two-dimensional list to a single dimension list, containing all the original elements of the sublists as a single list:

two_d_list = [[1,2,3],[4,5,6],[7,8,9]]
flattened = [item for sublist in two_d_list for item in sublist]
print(flattened) # prints [1, 2, 3, 4, 5, 6, 7, 8, 9]

This is known as “flattening” a list.

Explanation:

flattened = [
    item			# Item to be appended to flattened
    for sublist in two_d_list	# Loop through the list to get the sublists
    for item in sublist		# Loop through each sublist to get the item
]
print(flattened) # prints [1, 2, 3, 4, 5, 6, 7, 8, 9]

Note the order:

  • The item to append to the collection is referenced first
  • Sublists are then generated from the initial 2d list
  • Items are then generated from the sublist

References


comments powered by Disqus