Albert Han
Albert Han

Reputation: 119

Increment for loop by adding counter to itself

In java you can increment a for loop by adding the counter to itself.

for (int i = 1; i < 20; i += i)
    System.out.print(i + " ")
----
1 2 4 8 16

Is there a python equivalent? The following does not work.

for i in range(1, 10, i+=i):
    print(i, end=' ')
----
SyntaxError: invalid syntax

Another question came up during experimentation.

for i in range(1,10,i):
    print(i,end=' ')
print()

for i in range(1,20,i):
    print(i,end=' ')
print()

for i in range(1,30,i):
    print(i,end=' ')
print()

for i in range(1,40,i):
    print(i,end=' ')
print() 
----
1 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 
1 20 
1 21 

The main question is whether there is a python equivalent.
The other question is what is going on when the step is i.

Upvotes: 1

Views: 5600

Answers (2)

Barmar
Barmar

Reputation: 782285

You can define a generator that does it:

def doubleRange(start, end):
    while start < end:
        yield start
        start += start

for i in doubleRange(1, 10):
    print(i)

Upvotes: 5

user2357112
user2357112

Reputation: 281842

Python for loops are for-each loops, like Java's for (Type thing : container), not like Java's for (init; test; increment).

If you want an init-test-increment style loop in Python, you need to use while:

i = 1
while i < 10:
    # loop body
    i += i

Upvotes: 1

Related Questions