Python: one-line cartesian for-loop product

Do you know you can do this?

>>> [(x,y) for x in xrange(2) for y in xrange(5)] [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4)] 

This is neat. Is there a loop version for the loop, or can this be done only to understand the list?

EDIT: I think my question was misunderstood. I want to know if there is a special syntax for this:

 for x in xrange(2) <AND> y in xrange(5): print "do stuff here" print "which doesn't fit into a list comprehension" print "like printing x and y cause print is a statement", x, y 

I could do this, but it looks somewhat repetitive:

 for x,y in ((x,y) for x in xrange(2) for y in xrange(5)): print x, y 
+4
source share
2 answers

Well there is no syntax for what you want, but there is itertools.product .

 >>> import itertools >>> for x, y in itertools.product([1,2,3,4], [5,6,7,8]): print x, y ... 1 5 1 6 1 7 1 8 [ ... and so on ... ] 
+7
source

This is the equivalent, more compact version:

 def values(): for x in xrange(2): for y in xrange(5): yield (x, y) list(values()) 

Refresh . To compare the bytecode of both, do the following:

 import dis print dis.dis(values) # above function gen = ((x,y) for x in xrange(2) for y in xrange(5)) print dis.dis(gen.gi_code) 
+5
source

All Articles