Express a number as a sum of powers of 2 This is my function:

def two_powers(num):
    powers = []
    i = 1
    while i &lt;= num:
        if i &amp; num:
            powers.append(i)
        i &lt;&lt;= 1
    return powers


I have python 3.6(Windows 10 64-bit). I want the result in the form of a list. My problem statement is to express a integer(num) in the form of sum of powers of 2.

Do I have to create a list in the beginning and then append to it each time ? Can I return a list directly without creating it in the beginning ?

This will will speed up my execution time, right ?
List building performance aside, there is a way to get the powers of two out without touching the bits in between, by using the formulas:

isolateLowestSetBit(x) = x &amp; -x
resetLowestSetBit(x) = x &amp; (x - 1)


These have been explained elsewhere.

Using those definitions, you can extract the powers of two like this:

def two_powers(num):
    powers = []
    while num != 0:
        powers.append(num &amp; -num)
        num = num &amp; (num - 1)
    return powers


Since it potentially avoids testing many bits (depending on the size and sparseness of the input) it may be faster. It can also work out not so well, for very dense numbers.