Power of Two Check Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Power of Two Check runs in O(1) time and O(1) space, in Python as in every other language.
- ✓CPython has no is_power_of_two builtin. The primitives live on int itself: int.bit_count(), added in Python 3.10, returns the population count, so n.bit_count() == 1 is the direct test, and int.bit_length() gives the number of bits needed, so for a power of two the exponent is n.bit_length() - 1 (e.g.
- ✓Reviewers want the guard and the test in one expression: n > 0 and n & (n - 1) == 0. In Python & binds tighter than ==, so the extra parentheses that C and Java demand are noise here, and writing ((n & (n - 1)) == 0) reads as translated code.
- ✓The Python trap: bool subclasses int, so True survives every isinstance(n, int) check and True & (True - 1) == 0 evaluates to True: your validator accepts True as a legal buffer size.
- ✓Every int is a heap object, so n - 1 allocates a PyLongObject unless the result lands in the -5..256 small-int cache, and n & (n - 1) allocates the AND result too; interpreter dispatch dwarfs the two machine instructions the work actually needs.
What Power of Two Check actually is
Power of Two Check in Python: what you actually reach for
Python implementation
def is_power_of_two(n: int) -> bool:
"""True only for 1, 2, 4, 8, ... Rejects bools, zero and negatives."""
if isinstance(n, bool): # bool is a subclass of int
return False
if not isinstance(n, int) or n <= 0:
return False
return n & (n - 1) == 0 # '&' binds tighter than '==' in Python
def is_power_of_two_popcount(n: int) -> bool:
"""int.bit_count() requires Python 3.10 or newer."""
if isinstance(n, bool) or not isinstance(n, int) or n <= 0:
return False
return n.bit_count() == 1
if __name__ == "__main__":
assert is_power_of_two(1)
assert is_power_of_two(1 << 200) # arbitrary precision, still exact
assert not is_power_of_two(0)
assert not is_power_of_two(-8)
assert not is_power_of_two(True) # the trap this guard closes
import math
print(math.log2(2 ** 52 + 1).is_integer()) # True -- and it is a lie
print(is_power_of_two_popcount(2 ** 52 + 1)) # False -- the bit test is not
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Power of Two Check?
CPython has no is_power_of_two builtin. The primitives live on int itself: int.bit_count(), added in Python 3.10, returns the population count, so n.bit_count() == 1 is the direct test, and int.bit_length() gives the number of bits needed, so for a power of two the exponent is n.bit_length() - 1 (e.g. (8).bit_length() == 4). math.log2 exists but is a float route. Nothing needs importing for the bitwise form n & (n - 1) == 0. For arrays, numpy exposes no power-of-two predicate either; you write (a & (a - 1)) == 0 elementwise over a fixed-width dtype and inherit that dtype's wraparound.
What is the most common Python mistake when implementing Power of Two Check?
bool subclasses int, so True survives every isinstance(n, int) check and True & (True - 1) == 0 evaluates to True: your validator accepts True as a legal buffer size. Test isinstance(n, bool) first. The second Python-only twist is the opposite of overflow. Ints are arbitrary precision, so 1 << 10000 is a genuine power of two and the bitwise test still answers correctly, but the float route quietly does not: math.log2(2**52 + 1) rounds to exactly 52.0 on IEEE doubles, so .is_integer() reports a false positive that a machine-word integer path never produces.
How does Power of Two Check actually perform in Python?
Every int is a heap object, so n - 1 allocates a PyLongObject unless the result lands in the -5..256 small-int cache, and n & (n - 1) allocates the AND result too; interpreter dispatch dwarfs the two machine instructions the work actually needs. n.bit_count() is one method call producing one small int with no intermediate, which is why it wins decisively on large ints, where the AND has to allocate a multi-digit result; for machine-word ints the bitwise form is usually at least as fast, because the method lookup and call cost more than the two specialised binary ops. O(1) is honest only for machine-word-sized values: CPython stores ints in 30-bit digits, so the AND on a 10,000-bit value is linear in digit count. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Devin offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.