Nested for loops in Python

I want to do something like

for a in [0..1]: for b in [0..1]: for c in [0..1]: do something 

But I can have 15 different variables. Is there an easier way for example

 for a, b, c in [0..1]: do something 

Thanks for any help

+7
source share
3 answers

itertools.product :

 import itertools for a,b,c in itertools.product([0, 1], repeat=3): # do something 
+10
source

You can iterate over the product of all of them. Use itertools.product and go through the ranges.

 import itertools for i in itertools.product(range(2), range(3), range(2)): print (i) 

gives

 (0, 0, 0) (0, 0, 1) (0, 1, 0) (0, 1, 1) (0, 2, 0) (0, 2, 1) (1, 0, 0) (1, 0, 1) (1, 1, 0) (1, 1, 1) (1, 2, 0) (1, 2, 1) 
+3
source

It looks like you have a matrix / list of variables that you need to process. So the best (and fastest) solution is to use the matrix / list tool.

For example: Python package itertools .

As others have hinted, itertools.product is probably what you want. But, see the full list: http://docs.python.org/library/itertools.html

Good luck.

+1
source

All Articles