1

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?

0

2 Answers 2

4
import itertools
site_range=[0,1,2]
[x for x in itertools.product(site_range, repeat=len(site_range))]
Sign up to request clarification or add additional context in comments.

Comments

3

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.

5 Comments

That's not the cartesian product of [0,1], and that code doesn't even run. Another incorrect, untested answer accepted over a correct, tested one...
@Glenn: You are right on both accounts. The code was just intended to illustrate the use of the product function. To be honest to example was copied from the documentation of the function.
TypeError: 'int' object is not iterable. You need to use repeat=3 instead
@gnibbler: Thats what you get from posting python snippets without having an interpreter available for testing. Thanks.
Thanks to everybody. In fact I've accepted the very first version of it, which simply said "use itertools.product". Which was enough to get me, like, darn, RTFM before asking.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.