Count set bits using Python List comprehension

Set bits are the bits representing 1 in the binary form of a number. In this article we will see how to count the number of set bits in a given decimal number.

#53 in binary is: 110101
The number of set bits is the number of ones.
Here it is 4.

In the below program we take the number and convert it to binary. As the binary conversion contains 0b as the first two characters, we remove it using string splitting technique. Then use a for loop to count each bit of the binary number if that value of the digit is 1.


 Live Demo

value = 59
#Check the binary value
#Remove the first two characters
bitvalue = bin(value)[2:]
count = 0
for digit in bitvalue:
   if digit == '1':
      count = count+1
print("Length of set bits: ",count)


Running the above code gives us the following result −

Length of set bits: 5