Binary to decimal in python binaryToDecimal = lambda binary: sum([[int(2**index) for index in range(len(binary))][-index-1] for index, char in enumerate(binary) if int(char)])


I wrote a simple function that converts binary strings into decimal integers. How can this be improved/simplified?

I know about the int function, I wanted to implement the conversion myself.
Of course, the most efficient solution would be to let python parse the binary string as integer ;)

binaryToDecimal = lambda x: int(x,2)


But you already know that, so what about simplifying your code like this:

binaryToDecimal = lambda binary: sum(1&lt;&lt;(len(binary)-index-1) for index, char in enumerate(binary) if char=='1')



removing the creation of the inner list comprehension just to pick one value
not using power but bitshift (integer computation, faster, more accurate)
don't create a list to pass to sum, pass a generator comprehension (it's faster, saves memory)
in your condition, don't convert your number to integer, just test against the char value (it's faster)


Keep in mind that your parsing has no error checking!