Python Glossary Русский

Python 3.10+Numbers & mathfunction

int.bit_count

bits

Return the number of ones in the binary representation of the absolute value (population count). Added in 3.10.

Syntax

n.bit_count()

The method exists only from 3.10 on; on an older interpreter you get AttributeError and fall back to counting ones in the bin() string. The sign is ignored — negatives are counted by absolute value, not by a two's-complement pattern. A classic use is Hamming distance: XOR the two numbers and count the ones.

Examples

print((7).bit_count())    # → 3
print((255).bit_count())  # → 8
print((0).bit_count())    # → 0

See also

Open in the full glossarydocs.python.orgReport an inaccuracy