-1

I want to create a list of all possible booleans with a given length n, using Python 3.

# suppose n = 2
# the expected output should be
output = [[0, 0], [0, 1], [1, 0], [1, 1]]

In my real application, n is never larger than 10.

A similar post is here but for Java.

Could you please show me how to do it in Python 3? Thanks in advance.

aura
  • 383
  • 7
  • 24

1 Answers1

2

A good opportunity to leverage itertools:

def boolean_combinations(n):
    return [
        *itertools.product(
            *[range(2) for _ in range(n)]
    )]
N Chauhan
  • 3,407
  • 2
  • 7
  • 21
  • I did not get correct results with your code. When `n=2`, I got [(0, 0), (0, 1), (1, 1)]. It misses (1, 0). – aura May 27 '19 at 21:24