1

I need a list of strings representing binary values, with a fixed length, thus with leading zeros. for example:

my_list = ["00", "01", "10", "11"]

I want to be able to generate the list given the number of bits. I've come up with a code, but I'm not sure if this is the best way to do it and wonder if it's possible to do the same with a one-liner?

bits = 2
my_list = []
for i in range(2**bits):
    my_list.append(format(i, '0b').zfill(bits))
0

4 Answers 4

2

You can use itertools.product to accomplish this

from itertools import product 

def bitstrings(n):
    return [''.join(bits) for bits in product('01', repeat=n)]
Sign up to request clarification or add additional context in comments.

Comments

2

You could use itertools.product:

>>> from itertools import product
>>> [''.join(bs) for bs in product('01', repeat=2)]
['00', '01', '10', '11']
>>> [''.join(bs) for bs in product('01', repeat=3)]
['000', '001', '010', '011', '100', '101', '110', '111']

You could also specify the total string length directly in format:

>>> n = 2
>>> [format(i, '0%ib' % n) for i in range(2**n)]
['00', '01', '10', '11']
>>> n = 3
>>> [format(i, '0%ib' % n) for i in range(2**n)]
['000', '001', '010', '011', '100', '101', '110', '111']

Comments

1

All you need to do for a list comprehension is bring up the last line and make it a list:

>>> bits = 2
>>> l = [format(i, 'b').zfill(bits) for i in range(2**bits)]
>>> l
['00', '01', '10', '11']

So

for block1:
    block2

is

[block2 for block1]

Alternatively, you could use itertools.product, and map ''.join to make them into the right format:

>>> import itertools as it
>>> list(map(''.join, it.product('01', repeat=bits)))
['00', '01', '10', '11']

Comments

0

You can do this without using any imports and can use list comprehension to make it one line. I suggest using << instead of ** because it's much faster when dealing with binary numbers since it deals with the number in binary and then shifts it (1 << n is the same as 2**n) by n.

def bitstring(bits):
    return ["{:0{}b}".format(i, bits) for i in range(1 << bits)]

print(bitstring(2))

will return

['00', '01', '10', '11']

Comments

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.