joedborg
joedborg

Reputation: 18353

Python combine two for loops

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.

Upvotes: 20

Views: 43538

Answers (2)

eumiro
eumiro

Reputation: 213125

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

Upvotes: 35

Amandasaurus
Amandasaurus

Reputation: 60809

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

Upvotes: 16

Related Questions