1

I want to produce a list of lists that represents all possible combinations of the numbers 0 and 1. The lists have length n.

The output should look like this. For n=1:

[ [0], [1] ]

For n=2:

[ [0,0], [0, 1], [1,0], [1, 1] ]

For n=3:

[ [0,0,0], [0, 0, 1], [0, 1, 1]... [1, 1, 1] ]

I looked at itertools.combinations but this produces tuples, not lists. [0,1] and [1,0] are distinct combinations, whereas there is only one tuple (0,1) (order doesn't matter).

Any hints or suggestions? I have tried some recursive techniques, but I haven't found the solution.

martineau
  • 119,623
  • 25
  • 170
  • 301
Nate Reed
  • 6,761
  • 12
  • 53
  • 67
  • "I looked at itertools.combinations but this produces tuples, not lists." Converting tuples to lists is trivial. However, `itertools.combinations` is the wrong tool for the job described. – Karl Knechtel Mar 02 '23 at 00:00

4 Answers4

4

You're looking for itertools.product(...).

>>> from itertools import product
>>> list(product([1, 0], repeat=2))
[(1, 1), (1, 0), (0, 1), (0, 0)]

If you want to convert the inner elements to list type, use a list comprehension

>>> [list(elem) for elem in product([1, 0], repeat =2)]
[[1, 1], [1, 0], [0, 1], [0, 0]]

Or by using map()

>>> map(list, product([1, 0], repeat=2))
[[1, 1], [1, 0], [0, 1], [0, 0]]
Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71
2

Use itertools.product, assigning the repeat to n.

from itertools import product
list(product([0,1], repeat=n))

Demo:

>>> list(product([0,1], repeat=2))
[(0, 0), (0, 1), (1, 0), (1, 1)]
>>> list(product([0,1], repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
zhangyangyu
  • 8,520
  • 2
  • 33
  • 43
2
>>> from itertools import product
>>> list(product([0, 1], repeat=2))
[(0, 0), (0, 1), (1, 0), (1, 1)]
>>> 
>>> list(product([0, 1], repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

To get list of list, you can do:

>>> map(list, list(product([0, 1], repeat=2)))
[[0, 0], [0, 1], [1, 0], [1, 1]]
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

Just to add a bit of diversity, here's another way of achieving this:

>>> [map(int, format(i, "03b")) for i in range(8)]
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841