Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate all possible variable values in Python

Tags:

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.

like image 654
Moronic Avatar asked Apr 15 '26 05:04

Moronic


1 Answers

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)]
like image 138
wim Avatar answered Apr 16 '26 18:04

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!