0

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
  • 239,568
  • 38
  • 324
  • 436
Guy
  • 604
  • 5
  • 21
  • 1
    Just from the title, `itertools` is your friend. – rlms Feb 16 '14 at 15:09
  • The answer I got just now demonstrates that quite clearly :) – Guy Feb 16 '14 at 15:09
  • The canonical version of the question that was used as a duplicate before, is https://stackoverflow.com/questions/533905. However, we have a more specific duplicate (this is more of a "Cartesian exponent" than a Cartesian product), so I used one of those. – Karl Knechtel Feb 18 '23 at 16:43

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
  • 233,700
  • 52
  • 457
  • 497
  • 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