List comprehension for loops Python

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.


sum works here:

total = sum(x+y for x in (0,1,2,3) for y in (0,1,2,3) if 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))

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)