Check whether an integer is a power of two in Python
Redowan Delowar
January 21, 2022
To check whether an integer is a power of two, I've deployed hacks like this:
While this hex trick works, I've never liked explaining the pattern matching hack that's going on here.
Today, I came across this tweet by Raymond Hettinger where he proposed an elegant solution to the problem. Here's how it goes:
This is neat as there's no hack and it uses a mathematical invariant to check whether an integer is a power of 2 or not. Also, it's a tad bit faster.
Explanation
Any integer that's a power of 2, will only contain a single 1 in its binary representation.
For example:
The .bit_count() function checks how many on-bits (1) are there in the binary representation of an integer.
Complete example with tests
Discussion in the ATmosphere