53

In Python, how can I get all combinations of n binary values 0 and 1?

For example, if n = 3, I want to have

[ [0,0,0], [0,0,1], [0,1,0], [0,1,1], ... [1,1,1] ]  #total 2^3 combinations

How can I do this?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
LWZ
  • 11,670
  • 22
  • 61
  • 79
  • @eumiro, I think my question is also equivalent to this one, http://stackoverflow.com/questions/3252528/converting-a-number-to-binary-with-a-fixed-length , but that answer gives a string instead of a list. – LWZ Feb 18 '13 at 08:52

3 Answers3

97

Use itertools.product

import itertools
lst = list(itertools.product([0, 1], repeat=3))

This will yield a list of tuples (see here)

You can easily change this to use a variable repeat:

n = 3
lst = list(itertools.product([0, 1], repeat=n))

If you need a list of lists, then you can use the map function (thanks @Aesthete).

lst = map(list, itertools.product([0, 1], repeat=n))

Or in Python 3:

lst = list(map(list, itertools.product([0, 1], repeat=n)))
# OR
lst = [list(i) for i in itertools.product([0, 1], repeat=n)]

Note that using map or a list comprehension means you don't need to convert the product into a list, as it will iterate through the itertools.product object and produce a list.

Volatility
  • 31,232
  • 10
  • 80
  • 89
17

Without using any in-build functions or smart techniques we can get like this.

def per(n):
    for i in range(1<<n):
        s=bin(i)[2:]
        s='0'*(n-len(s))+s
        print (map(int,list(s)))
per(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]
ZF007
  • 3,708
  • 8
  • 29
  • 48
Anil
  • 578
  • 4
  • 12
4

Following will give you all such combinations

bin = [0,1]
[ (x,y,z) for x in bin for y in bin for z in bin ]
MoveFast
  • 3,011
  • 2
  • 27
  • 53