Python: All powers of 2 from the power of 0 to 16

bwormz picture bwormz · Apr 22, 2017 · Viewed 9.1k times · Source

I'm trying to program in Python so that I can print the results of 2 to the power of every number from 0 to 16. I have code below so far, but it can only print the result of 2 to the power 16 and nothing before it. How do I print the other answers with it?


n = 2
exponent = 16

while exponent < 16+1:
  n = n ** exponent
  exponent = exponent + 1
  print (n)

Answer

Jean-Fran&#231;ois Fabre picture Jean-François Fabre · Apr 22, 2017

best way with powers of 2 is using bit-shifting on 1, which is way faster than exponentiation in that case.

That said, I wouldn't recommend a while loop but rather a for loop, or even better: generate your list of values using a list comprehension (which avoids all the variables and undesired side effects, infinite loops because of while, etc...) and one-liner:

print([1<<exponent for exponent in range(17)])

result:

[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536]