ZtoYi ZtoYi - 5 months ago 11
Python Question

Python List Comprehension with Sum

I have some python code that looks like this:

mat = [[3], [4], [4], [0], [1, 2]]
nwalls = 5*[1]
for i in range(1,3):
nwalls = [sum(nwalls[k] for k in mat[j]) for j in range(5)]
# nwalls = [1, 2, 2, 1, 2]


I can't for the life of me unroll this into syntax without using list comprehension for me to understand. Please assist.

Answer

The direct translation would be

mat = [[3], [4], [4], [0], [1, 2]]
nwalls = 5*[1]
for i in range(1, 3):
    _nwalls = []
    for j in range(5):
        tot = 0                # - sum
        for k in mat[j]:       #  /
            tot += nwalls[k]   # /
        _nwalls.append(tot)
    nwalls = _nwalls

(nwalls[k] for k in mat[j]) it self is a generator, in python repl, you can check it as:

>>> y = (x for x in range(10))
>>> type(y)
<class 'generator'>

and sum can take a generator, as sum( (x for x in range(10)) ), and as PEP289 said

if a function call has a single positional argument, it can be a generator expression without extra parentheses, but in all other cases you have to parenthesize it.

so it looks like sum(x for x in range(10))