Skip to content Skip to sidebar Skip to footer

Itertools Equivalent Of Nested Loop "for X In Xs: For Y In Ys..."

I have a nested loop to create all combinations in a set of conjugated verbs. The aim to to get all possible combinations of verb, person and tense, e.g. [['to be', 'first person s

Solution 1:

for v, p, t in itertools.product(verbs, persons, tenses):
    ...

Solution 2:

You can use itertools.product for this task:

Cartesian product of input iterables. Equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

a = [1,2,3]
b = [4,5,6]
c = [7,8,9]
import itertools
for p in itertools.product(a,b,c):
    print(p)

The alternative would be a list comprehension expression:

forpin [(x,y,z) forxin a foryin b forzin c]:
    print(p)

Post a Comment for "Itertools Equivalent Of Nested Loop "for X In Xs: For Y In Ys...""