Generating permutations

Question:

I need to generate a list of variable length listing all possible values of a n-length tuple with each value either 0 or 1. Thus there are 2^n possible tuples. For example, for an input of n=3 my list should look like

a=[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), 
(1, 1, 1)]

Note: It doesn’t matter if the inner elements are tuples, use lists if convenient. It also doesn’t matter much if the final list isn’t sorted as per my example. I currently can do it using a for loop, but was wondering if there is some better, more pythony approach to this. This is the code I wrote.

>>>>newlist=[]
>>>>for i in range(2**n):
          s=bin(i)[2:] #spliced to remove the leading '0b' in the string
          s='0'*(n-len(s))+s #adding extra zeroes to beginning of string
          buffer=tuple(int(i) for i in s)
          newlist.append(buffer)

That generates the list I wanted. Any suggestions to do it in a better, one-liner way?

Asked By: Guy

||

Answers:

You can use itertools.product, like this

from itertools import product
print list(product(range(2), repeat = 3))

Output

[(0, 0, 0),
 (0, 0, 1),
 (0, 1, 0),
 (0, 1, 1),
 (1, 0, 0),
 (1, 0, 1),
 (1, 1, 0),
 (1, 1, 1)]
Answered By: thefourtheye
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.