views:

43

answers:

2

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?

+3  A: 

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.

Space_C0wb0y
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 Maynard
@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.
Space_C0wb0y
@space, `TypeError: 'int' object is not iterable`. You need to use `repeat=3` instead
gnibbler
@gnibbler: Thats what you get from posting python snippets without having an interpreter available for testing. Thanks.
Space_C0wb0y
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.
Zhenya
+3  A: 
import itertools
site_range=[0,1,2]
[x for x in itertools.product(site_range, repeat=len(site_range))]
Glenn Maynard
@Glenn: Re-accepted your answer. Thanks a lot!
Zhenya