Making a list with every possible combination of 0's and 1's in Python

python

Solution

Use `itertools.product`:

import itertools

for numbers in itertools.product([0, 1], repeat=3):
    print(numbers)

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)

Problem

I am trying to iterate over every possible combination of 0's and 1's in a list. For example, if I was working with 3 parameters, I would get: ``` [0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 0], [1, 0, 1], [0, 1, 1], [1, 1, 1] ``` I thought the solution on Array combinations of 0s and 1s was inadequate due to the problems with storing binary numbers of the length I need. I would like to be able to iterate over lists like this for lengths of 20 or more, where the sheer size becomes hard to deal with in integers. I have been using code like this: ``` for a in [0, 1]: for b in [0, 1]: for c in [0, 1]: print([a, b, c]) ``` Is there something more Pythonic or quick? A 20-deep nested loop, even a simple one like this, is still a monster.

Original source