Search code examples
pythoninlinelist-comprehension

List comprehension for loops Python


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

Solution

  • sum works here:

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