List comprehension for loops Python

disruptive picture disruptive · Oct 21, 2011 · Viewed 59.5k times · Source

I use a lot of N dimensional arrays and it gets a pain to have to write such indented code and I know some codes can be replaced with list comprehensions and inline statements. For example:

for x in (0,1,2,3):
    for y in (0,1,2,3):
        if x < y:
            print (x, y, x*y)

can be replaced with:

print [(x, y, x * y) for x in (0,1,2,3) for y in (0,1,2,3) if x < y]

But how could I change the action instead of print to do something else like:

total = x+y

So what I want to do is something like:

[(total+=x+y) for x in (0,1,2,3) for y in (0,1,2,3) if x < y]

However this doesn't work

Is there a smart way to do this rather than:

for x in (0,1,2,3):
        for y in (0,1,2,3):
            if x < y:
                total+=x+y

Answer

Jochen Ritzel picture Jochen Ritzel · Oct 21, 2011

sum works here:

total = sum(x+y for x in (0,1,2,3) for y in (0,1,2,3) if x < y)