# 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.

• what about using python: binaryToDecimal = lambda x: str(int(x,2)) Commented May 9, 2018 at 18:41
• I'm aware that you can do that :) I just wanted to implement it myself Commented May 9, 2018 at 18:41
• Well, readability could be improved a lot by not using too much list comprehensions together :) Commented May 9, 2018 at 18:42
• Definitely, I did that on purpose though to make it as compact as possible Commented May 9, 2018 at 18:43
• I added reinventing-the-wheel, because that's what you're doing here: inventing this even though a standard implementation exists. In the future, you may want to add this tag yourself, to signify to other users that you're knowingly not using the standard implementation. Commented May 9, 2018 at 19:28

Of course, the most efficient solution would be to let python parse the binary string as integer ;)

binaryToDecimal = lambda x: int(x,2)


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

• don't create a list to pass to sum, pass a generator comprehension (it's faster, saves memory)