1

I was playing around with Python 2.7 and wanted to know if there was a clean way to code a Python equivalent of this Java loop (where you can modify the increment value in the loop):

for (int i = 1; i <= 64; i *= 2) {
    # i = 1, 2, 4, 8, 16, 32, 64
}

It seems like in Python you can use range(), but you can only get every nth element (e.g. for i in range(1, 65, 2) will get you every odd element).

1
  • 1
    Not exactly a duplicate, but you may find dicussion on this question helpful. Commented Nov 21, 2015 at 8:13

1 Answer 1

2

Java for loops are different from Python's. You an use a while loop for the same effect.

i = 1
while (i<=64):
    print(i)
    i*=2

Else you can implement your own range function using a custom generator

>>> def my_own_range(n):
...     i = 1
...     while(i<=n):
...         yield(i)
...         i*=2
... 
>>> for i in my_own_range(64):
...     print(i)
... 
1
2
4
8
16
32
64
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.