Moronic
Moronic

Reputation: 133

Generate all possible variable values in Python

What is the most pythonic way of getting the following:

(False, False, False)
(False, False, True)
(False, True, False)
(False, True, True)
...

I have n variables, each taking a value True or False, how can I combine these? I was thinking of using range(n) and then checking the bits of generated integers, but this seems too hacky.

Upvotes: 2

Views: 625

Answers (1)

wim
wim

Reputation: 363063

Probably simplest:

>>> list(itertools.product([False, True], repeat=3))

[(False, False, False),
 (False, False, True),
 (False, True, False),
 (False, True, True),
 (True, False, False),
 (True, False, True),
 (True, True, False),
 (True, True, True)]

Upvotes: 10

Related Questions