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

1 Answer 1

2

A good opportunity to leverage itertools:

def boolean_combinations(n):
    return [
        *itertools.product(
            *[range(2) for _ in range(n)]
    )]
Sign up to request clarification or add additional context in comments.

1 Comment

I did not get correct results with your code. When n=2, I got [(0, 0), (0, 1), (1, 1)]. It misses (1, 0).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.