Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python combine two for loops

Tags:

python

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.

like image 883
joedborg Avatar asked Feb 22 '12 12:02

joedborg


People also ask

How do I combine two for loops?

num = 224 list1 = [] for i in range(2, num): if num % i == 0: list1. append(i) for i in range(2, num): if num % i == 0: print(num, 'is not prime and can be divided by the following numbers:\n', list1) break else: print(num, 'is Prime. ')

How do you connect two for loops in Python?

First, Write an outer for loop that will iterate the first list like [for i in first] Next, Write an inner loop that will iterate the second list after the outer loop like [for i in first for j in second] Last, calculate the addition of the outer number and inner number like [i+j for i in first for j in second]

Can you combine for statements in python?

You can combine multiple print statements per line using, in Python 2 and use the end argument to print function in Python 3.

Does Python loop start at 0?

Python for loop index start at 0 In Python by default, the range starts from 0 and ends at the value of the passed argument as -1.


2 Answers

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
like image 119
eumiro Avatar answered Sep 20 '22 17:09

eumiro


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
like image 35
Amandasaurus Avatar answered Sep 21 '22 17:09

Amandasaurus