List comprehension for loops Python

Each Answer to this Q is separated by one/two green lines.

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

sum works here:

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

As an alternative to writing loops N levels deep, you could use itertools.product():

In [1]: import itertools as it

In [2]: for x, y in it.product((0,1,2,3),(0,1,2,3)):
   ...:     if x < y:
   ...:         print x, y, x*y

0 1 0
0 2 0
0 3 0
1 2 2
1 3 3
2 3 6

This extends naturally to N dimensions.

Use numpy. This lets you use arrays that add up like vectors:

x = numpy.arange(3)
y = numpy.arange(3)
total = x + y

With the modified question, add a call to sum as well

total = numpy.sum(x+y)

Reduce function directly reduces collective items to single item. You can read more about them here, but this should work for you:

total=reduce(lambda x,y:x+y,range(4))

or

total=reduce(lambda x,y:x+y,(0,1,2,3))

Another possibility is:

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

In this way you can iterate over anything you’d use in a list comprehension without actually creating the comprehended list (if you get my meaning 😉 If comprehended list is big, maybe so big it saturates or even doesn’t fit in memory, that’s quite handy..


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .