In Python, how can I get all combinations of n
binary values 0
and 1
?
For example, if n = 3
, I want to have
[ [0,0,0], [0,0,1], [0,1,0], [0,1,1], ... [1,1,1] ] #total 2^3 combinations
How can I do this?
A binary digit is called a bit. There are two possible states in a bit, usually expressed as 0 and 1. A series of eight bits strung together makes a byte, much as 12 makes a dozen. With 8 bits, or 8 binary digits, there exist 2^8=256 possible combinations.
There are 128 'binary numbers' with 7 digits. For a given position, half have 0, half have 1 in that position.
There are several methods: 2^n where n is the number of bits (2^8) Each bit has 2 possibilities. Unsigned value of all 1's + 1 (255 + 1) Count up from 0 to max value (all ones) + zero.
Use itertools.product
import itertools lst = list(itertools.product([0, 1], repeat=3))
This will yield a list of tuples (see here)
You can easily change this to use a variable repeat
:
n = 3 lst = list(itertools.product([0, 1], repeat=n))
If you need a list of lists, then you can use the map
function (thanks @Aesthete).
lst = map(list, itertools.product([0, 1], repeat=n))
Or in Python 3:
lst = list(map(list, itertools.product([0, 1], repeat=n))) # OR lst = [list(i) for i in itertools.product([0, 1], repeat=n)]
Note that using map
or a list comprehension means you don't need to convert the product into a list, as it will iterate through the itertools.product
object and produce a list.
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