Is there a way to use itertools in python to clean up nested iterations?

iterator, nested-loops, python, python-itertools

Solution

Use `itertools.product` within a list comprehension:

In [1]: from itertools import product
In [5]: [i*j*k for i, j, k in product(a, b, c)]
Out[5]: 
[6,
 10,
 14,
 12,
 20,
 28,
 18,
 30,
 42,
 12,
 20,
 28,
 24,
 40,
 56,
 36,
 60,
 84,
 18,
 30,
 42,
 36,
 60,
 84,
 54,
 90,
 126]

Problem

Let's say I have the following code: ``` a = [1,2,3] b = [2,4,6] c = [3,5,7] for i in a: for j in b: for k in c: print i * j * k ``` Is there a way I can consolidate an iterator in one line instead of making it nested?

Original source

Related problems