List comprehension for loops Python List comprehension for loops Python python python

List comprehension for loops Python


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 itIn [2]: for x, y in it.product((0,1,2,3),(0,1,2,3)):   ...:     if x < y:   ...:         print x, y, x*y0 1 00 2 00 3 01 2 21 3 32 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)