how do I generate a cartesian product of several variables using python iterators?
Question: 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?


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

