8

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 might have 15 different variables. Is there a simpler way like

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

Thanks for any help

asked Aug 23, 2011 at 16:14

3 Answers 3

12

itertools.product:

import itertools
for a,b,c in itertools.product([0, 1], repeat=3):
 # do something
answered Aug 23, 2011 at 16:15
Sign up to request clarification or add additional context in comments.

1 Comment

My only complaint is it took so long for you to answer. There was a period of about 30 seconds where I was in limbo.
4

You can iterate over the product of all of them. Use itertools.product and pass in your ranges.

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

yields

(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)
answered Aug 23, 2011 at 16:15

Comments

1

It sounds like you have a matrix/list of variables you need to process. Thus, the best (and speediest) solution is to use a matrix/list tool.

Such as: The Python itertools package.

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

Good luck.

answered Aug 23, 2011 at 16:20

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.