List comprehensions

In Python there is a special way to initialize lists (and dictionaries) called list comprehensions. For many lists that we are going to create, list comprehensions are the recommended way to do so without using loops (remember that loops are slow in Python).

Another reason to use list comprehensions is that they can be elegant and resemble the way we would define sets in mathematical notation. Consider for instance the examples from this tutorial:

$V = (1, 2, 4, 8, \dots, 2^{12})$

$S = \{x^2 : x \in \{0 \dots 9\}\}$

$M = \{x | x \in S \textrm{ and } x \textrm{ even }\}$

We can initialize $V$, $S$ and $M$ easily with list comprehensions:


In [ ]:
V = [2**i for i in range(13)]
print V

In [ ]:
S = set([x**2 for x in range(10)])
print S

In [ ]:
M = set([x for x in S if x % 2 == 0])
print M

Complex example

In the introduction notebook there was an exercise that we tend to solve with loops and if-else statements as in other languages. The more pythonic way however would be with list comprehensions.

Create a list A with even and a list B with odd numbers between 0 and 20 (both exklusive)


In [ ]:
A = [i for i in range(1, 20) if i%2 == 0]
B = [i for i in range(1, 20) if i%2 == 1]
print A
print B

Print all numbers of list B that divide a number in A

For a given number we can check how many numbers it divides in A like this:


In [ ]:
def is_divider_of_a(b):
    return len([a for a in A if a%b==0]) > 0

print is_divider_of_a(3)

This way the task above can be formulated as a list comprehension like this:


In [ ]:
print [b for b in B if is_divider_of_a(b)]

Exercise

Project Euler is a website with many small mathematical challenges. Solve the first one with a list comprehension and np.sum():

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

If you like, you can make an account on their website and submit the solution.


In [ ]:
import numpy as np
# your code here

In [ ]:
# our solution
from solutions import *
decrypt_solution(solution_list_comprehensions, passphrase='foo')