1

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?

John Zwinck
  • 223,042
  • 33
  • 293
  • 407
Guy
  • 595
  • 2
  • 21

1 Answers1

4

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)]
thefourtheye
  • 221,210
  • 51
  • 432
  • 478
  • 1
    whoa. I had no idea this even existed. Thanks a lot. Need to read about the itertools module. I am going to accept this as soon as it lets me :D – Guy Feb 16 '14 at 15:09