
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
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.
Example
value = 59 #Check the binary value print(bin(value)) #Remove the first two characters bitvalue = bin(value)[2:] print(bitvalue) count = 0 for digit in bitvalue: if digit == '1': count = count+1 print("Length of set bits: ",count)
Output
Running the above code gives us the following result −
0b111011 111011 Length of set bits: 5
- Related Articles
- Python List Comprehension?
- Python Count set bits in a range?
- Python List Comprehension and Slicing?
- Nested list comprehension in python
- Python Program to Count set bits in an integer
- K’th Non-repeating Character in Python using List Comprehension and OrderedDict
- Check if bits of a number has count of consecutive set bits in increasing order in Python
- Count set bits in an integer in C++
- Count set bits in a range in C++
- Move all zeroes to end of the array using List Comprehension in Python
- Java Program to Count set bits in an integer
- Python program to count total set bits in all number from 1 to n.
- How will you explain Python for-loop to list comprehension?
- How to create a dictionary with list comprehension in Python?
- How to catch a python exception in a list comprehension?

Advertisements