'Is there a way to shorten this code to fewer lines?

some_var = 0
for i in range(16):
    if 0x7777 >> i & 1:
        some_var += 1

Is there a way to shorten this code to use fewer lines? It's a simple variable I want to declare, and just out of curiosity, I'm wondering if I could do something like this in fewer lines.



Solution 1:[1]

some_var = sum(1 if (0x7777>> i & 1) else 0 for i in range(16))

(edit) recommended improvement ;-)

# Count the nonzero bits in 0x7777
some_var = sum(...)

Solution 2:[2]

Or some_var = sum(1 for i in range(16) if (0x7777>> i & 1))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Julien