Skip to content
scipython.com

Q4.3.2Mystery list comprehension

What does the following code do and how does it work?

>>> nmax = 5
>>> x = [1]
>>> for n in range(1,nmax+2):
...     print(x)
...     x = [([0]+x)[i] + (x+[0])[i] for i in range(n+1)]
...
Show solution

The code snippet outputs the first nmax+1 rows of Pascal's Triangle:

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]

In the list comprehension assignment,

x = [([0]+x)[i] + (x+[0])[i] for i in range(n+1)]

the elements of two lists are added. The two lists are formed from the array representing the previous row by, in the first case adding a 0 to the beginning of the list, and in the second case by adding a 0 to the end of the list. In this way, the sum is taken over neighbouring pairs of numbers, with the end numbers unchanged. For example, if x is [1, 3, 3, 1], the next row is formed by summing the elements in the lists

[0, 1, 3, 3, 1]
[1, 3, 3, 1, 0]

which yields the required [1, 4, 6, 4, 1].