2

Consider a tuple v = (a,b,c) and a generator function generate(x) which receives an item from the tuple and generates several options for each item.

What is the pythonic way of generating a set of all the possible combinations of the result of generate(x) on each item in the tuple?

I could do this:

v = (a,b,c)
for d in generate(v[0]):
    for e in generate(v[1]):
        for f in generate(v[2]):
            print d,e,f

but that's just ugly, plus I need a generic solution.

1 Answer 1

8

Python 2.6 has the function itertools.product() that does what you want:

import itertools
v = (a, b, c)
for d, e, f in itertools.product(*(generate(x) for x in v)):
  print d, e, f

From the docs:

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).

Sign up to request clarification or add additional context in comments.

3 Comments

Looks to be helpful, how would I iterate over the result?
@Yuval: for i in product(*(generate(x) for x in v)): do_whatever_you_want(i)
@Yuval: It returns a generator that lists all combinations. I've updated my answer to show how to iterate over the results.

Your Answer

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.