Question

I require the capability to do nested loops over various lists, for example:

A = [1,2,3]
B = [1,2,3]
C = [1,2,3]

for a in A:
   for b in B:
      for c in C:
         #do something

What I want to have some code that can take the list of lists given by [A]+[B]+[C] and loop over every sample path (i.e. the same thing as the above nested loops is doing).

It is okay if this code takes up 2 or 3 lines, since in my real world example I have not just A,B,C but also D,E,F,G,... so doing a nested loop as above is way too tedious.

Was it helpful?

Solution

You are looking for the product of the three lists; using itertools.product() lets you collapse the three nested loops to:

from itertools import product

for a, b, c in product(A, B, C):

Because A == B == C here, you could simplify that further to:

for a, b, c in product(A, repeat=3):

If you have multiple lists to produce a product of, put them in a list so you can produce the product of a variable number of input lists:

lists = [A, B, C, D, E]
for combination in product(*lists):

OTHER TIPS

You want a cartesian product from itertools:

from itertools import product
for x in product(A,B,C):
   print x
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top