17

Currently I would do:

for x in [1,2,3]:
    for y in [1,2,3]:
        print x,y

Is there way of doing something like below,

for x,y in ([1,2,3],[1,2,3]):
    print x,y

Would like to shorten this kind of loop and this throws the "too many to unpack" exception.

i.n.n.m
  • 2,936
  • 7
  • 27
  • 51
joedborg
  • 17,651
  • 32
  • 84
  • 118

2 Answers2

32

Use itertools.product

import itertools
for x, y in itertools.product([1,2,3], [1,2,3]):
    print x, y

prints all nine pairs:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

UPDATE: If the two variables x and y are to be chosen from one list, you can use the repeat keyword (as proposed by agf):

import itertools
for x, y in itertools.product([1,2,3], repeat=2):
    print x, y
eumiro
  • 207,213
  • 34
  • 299
  • 261
  • 8
    or `product([1, 2, 3], repeat=2)`. – agf Feb 22 '12 at 13:00
  • @agf: thanks! I always used `product(**[1,2,3]*2)`. I might still use my method because it's more explicit, but `repeat=...` might be more readable. – ninjagecko Feb 22 '12 at 13:27
  • @ninjagecko I assume you mean `product(*[[1,2,3]]*2)`, but I don't see that as more explicit. As you've shown, it's also easier to get wrong. Shameless self promotion: See my highly upvoted answer to [What is the best way to generate all possible three letter strings?](http://stackoverflow.com/a/7074066/500584) – agf Feb 22 '12 at 16:59
  • @agf: Ah yes, I meant `product(*[ [1,2,3] ]*2)`. I feel it's more explicit because `repeat=` requires the user to know about what that keyword does, but `repeat=` is pretty elegant. =) Nice answer; exactly how I'd do it. – ninjagecko Feb 23 '12 at 17:09
  • if the length is difference in that case – user765443 Oct 08 '13 at 08:00
16

You could use a generator expression in the for loop:

for x, y in ((a,b) for a in [1,2,3] for b in [5,6,7]):
  print x, y
Amandasaurus
  • 58,203
  • 71
  • 188
  • 248
  • FWIW - please include a reference to "generator expression". Your answer was the one that helped me today. About 8 yeas later. :) Thank you! – Rikki Feb 26 '21 at 04:26