4

Did 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)]

It's neat. Is there a for loop version or can one only do this for list comprehensions?

EDIT: I think my question was misunderstood. I want to know if there is 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 seems a bit repetitive:

for x,y in ((x,y) for x in xrange(2) for y in xrange(5)):
    print x, y
Claudiu
  • 224,032
  • 165
  • 485
  • 680

2 Answers2

10

Well there's 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 ... ]
senderle
  • 145,869
  • 36
  • 209
  • 233
5

That is an equivalent, more compact version of:

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

Update: To compare bytecode of both, do this:

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)
samplebias
  • 37,113
  • 6
  • 107
  • 103
  • is that an exact equivalent? (does python actually make a generator for every list comprehension?). otherwise, of course the output would be the same – Claudiu Apr 22 '11 at 20:40
  • Yep, the bytecode is pretty close although I think the generator is a bit more efficient. – samplebias Apr 22 '11 at 20:44
  • Well, of course it doesn't define a full throwaway generator for every list comprehension. It also won't unroll it into a python-level loop. But such implementation details don't matter, and neither does the fact that this example defines a generator. It's the nesting of loops that matters. (Edit: To nitpick, OP is using a list comprehension, which is implemented differently with special bytecodes!) –  Apr 22 '11 at 20:45
  • @delnan: ah depends on the level of the question. i agree initially it looked like i didnt know what nesting was, but it is pretty obvious to me - so taking the equivalence of the output as a given i was seeing if there was something more to your answer. thats a neat trick with looking at the byte-code! – Claudiu Apr 22 '11 at 20:50