Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modifying iterator in for loop in python [duplicate]

Tags:

python

@ Padraic Cunningham Let me know if you want me to delete the question.

I am new to python. I want to skip some iterator values based on some condition. This is easy in C but in python I am having a hard time.

So please help me in understanding why the code here loops 100 times instead of 10.

 for i in range(100):
    print i
    i = i +10

edit: I understand there is option to change step size of for loop. But I am interested in dynamically changing the iterator variable, like we can do in C. Okay, i get it, for loop is different in python than in C. Easy way to do is use the while loop, I did that in my code and it worked. Thank you community!

like image 328
physicist Avatar asked Dec 08 '22 22:12

physicist


2 Answers

The for loop is walking through the iterable range(100).

Modifying the current value does not affect what appears next in the iterable (and indeed, you could have any iterable; the next value might not be a number!).

Option 1 use a while loop:

i = 0
while i < 100:
    i += 4

Option 2, use the built in step size argument of range:

 for i in range(0,100,10):
       pass

This example may make it clearer why your method doesn't make much sense:

for i in [1,2,3,4,5,'cat','fish']:
    i = i + i
    print i

This is entirely valid python code (string addition is defined); modifying the iterable would require something unintuitive.

See here for more information on how iterables work, and how to modify them dynamically

like image 197
en_Knight Avatar answered Dec 10 '22 11:12

en_Knight


To do this use a while loop. Changing the iterator in a for loop will not change the amount if times it iterates Instead you can do

i=0
while i < 100:
    print i
    i = i +10
like image 27
nathan.medz Avatar answered Dec 10 '22 10:12

nathan.medz