Let\'s a=109
or 1101101
in binary. How do I iterate over bits of this number, eg: [64, 32, 8, 4, 1]
The efficiency of F.J.'s answer can be dramatically improved.
from itertools import count,takewhile
[2**i for i in takewhile(lambda x:109>2**x,count()) if 109&2**i][::-1]
I like one liners :)
I did a quick timeit.Timer.timeit() against this and @Duncan. Duncan still wins but not the one liner is at least in the same class.
from timeit import Timer
duncan="""\
def bits(n):
while n:
b=n&(~n+1)
yield b
n^=b
"""
Duncan=Timer('list(bits(109))[::-1]',duncan)
Duncan.timeit()
4.3226630687713623
freegnu=Timer('[2**i for i in takewhile(lambda x:109>2**x,count()) if 109&2**i][::-1]','from itertools import count,takewhile')
freegnu.timeit()
5.2898638248443604