This does what I want it to do:
import itertools
list(itertools.product(*[[0,1]]*4))
Output:
[(0, 0, 0, 0),
(0, 0, 0, 1),
(0, 0, 1, 0),
(0, 0, 1, 1),
(0, 1, 0, 0),
(0, 1, 0, 1),
(0, 1, 1, 0),
(0, 1, 1, 1),
(1, 0, 0, 0),
(1, 0, 0, 1),
(1, 0, 1, 0),
(1, 0, 1, 1),
(1, 1, 0, 0),
(1, 1, 0, 1),
(1, 1, 1, 0),
(1, 1, 1, 1)]
But it's a bit obfuscated to me. Is there a more pythonic way to do it?
itertools.product
takes a repeat
argument which simplifies it a bit as it avoids the argument unpacking and therefor the list multiplication:
itertools.product(range(2), repeat=4)
This is even called out in the official documentation1 (though the example uses repeat=3
).
1Note, I used range(2)
rather than (0, 1)
or [0, 1]
since that's how it's written in the documentation. Either way will work :) (obviously)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With