ev-br
ev-br

Reputation: 26040

how do I generate a cartesian product of several variables using python iterators?

Dear all, Given a variable that takes on, say, three values, I'm trying to generate all possible combinations of, say, triplets of these variables.

While this code does the trick,

site_range=[0,1,2]
states = [(s0,s1,s2) for s0 in site_range for s1 in site_range for s2 in site_range]

it's somewhat, uhm, clumsy, and is only getting worse if I try to do the same for combinations of more than three variables

Hence, my Python 101 questions:

  1. How do I go about rewriting the code above using iterators? I mean, is it possible to have an iterator which would yield the elements of the "states" above?

  2. Is it possible to extend this for generating not only triplets, but also 4-plets, 5-plets and so on?

Upvotes: 1

Views: 848

Answers (2)

Björn Pollex
Björn Pollex

Reputation: 76828

Use itertools.product:

>>> site_range=[0,1]
>>> list(product(site_range, repeat=3))
[000 001 010 011 100 101 110 111]

Edit As @Glenn Maynard points out in a comment, this is not the cartesian product. For this, you will have to check his answer.

Upvotes: 3

Glenn Maynard
Glenn Maynard

Reputation: 57484

import itertools
site_range=[0,1,2]
[x for x in itertools.product(site_range, repeat=len(site_range))]

Upvotes: 4

Related Questions