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.

1
  • "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. Commented Mar 2, 2023 at 0:00

4 Answers 4

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]]
Sign up to request clarification or add additional context in comments.

Comments

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)]

Comments

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]]

1 Comment

Great, I just need to convert those to lists, which is trivial.
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]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.