Jos
Jos

Reputation: 41

create a list of strings representing binary values, with a fixed length

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))

Upvotes: 1

Views: 287

Answers (4)

rassar
rassar

Reputation: 5670

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']

Upvotes: 1

AcesOfGlory
AcesOfGlory

Reputation: 46

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']

Upvotes: 0

Eric Duminil
Eric Duminil

Reputation: 54263

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']

Upvotes: 2

Patrick Haugh
Patrick Haugh

Reputation: 61032

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)]

Upvotes: 2

Related Questions