2

I have a list of bools and I want to convert it to a single int. For example: [True, True, False, True, False] -> 010112 -> 1110

I found this question: How do I convert a boolean list to int? but it's in C# and that doesn't help me.

My first try was to do

def bools2int(bools):
    n = 0
    for b in bools[::-1]:
        n *= 2
        n += b
    return n

which works.

But is there a more pythonic way to do this? And can it be done in one line?

  • Your `bools2int` function returns 52 for the example you gave, not 11. That makes it pretty much impossible to guess what you're really trying to do. Try more careful explanation, with clear examples? – Tim Peters Sep 06 '19 at 02:20
  • 1
    So your intent is that the input is a list of bits in the binary representation, least-significant bit first? That's fine if so, but then your `bools2int` doesn't at all implement that, so the question is still inherently confused. – Tim Peters Sep 06 '19 at 02:23
  • 1
    I'm sorry about that, I fixed the function, it should work as intended. – PlesleronTepryos Sep 06 '19 at 02:31

2 Answers2

6

IIUC, using built-in int(x, base=2):

l = [True, True, False, True, False]

def bool2int(bools):
    return int(''.join(str(int(i)) for i in reversed(bools)), 2)
bool2int(l)

Output:

11
Chris
  • 29,127
  • 3
  • 28
  • 51
0

After some messing around, I found this

sum([b << i for i, b in enumerate(bools)])

which I think is a very pythonic solution.