11

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 singular', 'future'],['to be', 'second person singular', 'future'], ...].

for v in verbs:
    for p in persons:
        for t in tenses:
            return [v, p, t]

Is there a way of reducing the nesting, perhaps using itertools?

Jamie Bull
  • 12,889
  • 15
  • 77
  • 116
  • related: [Equivalent Nested Loop Structure with Itertools](http://stackoverflow.com/q/15037175/4279) – jfs Mar 25 '14 at 20:36

2 Answers2

25
for v, p, t in itertools.product(verbs, persons, tenses):
    ...
Jayanth Koushik
  • 9,476
  • 1
  • 44
  • 52
6

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:

for p in [(x,y,z) for x in a for y in b for z in c]:
    print(p)
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88