6

@ 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!

physicist
  • 844
  • 1
  • 12
  • 24
  • 1
    Even in C, it is _always_ a bad idea to modify the iterating variable during a loop. – Akshat Mahajan Apr 15 '16 at 20:12
  • Based on the code you have shown, you should read the docs on [range](https://docs.python.org/3/library/functions.html#func-range). Look at what `step` does. – idjaw Apr 15 '16 at 20:13
  • I understand I can change the step size to 10, but I want to change the step size arbitrarily during run time, lets say inside some 'if conditions'. I also understand it is a bad idea to change the iterating variable, but I still wish to do that. – physicist Apr 15 '16 at 20:16
  • @AkshatMahajan There is a valid reason for this: I am processing a string that has been split, and in some cases I want to join two of the parts, e.g. I want to join '+' with the '5' that follows it. Then when I find the plus, I append the 5 and increase the variable in order to skip the 5. I am sure there are other valid situations. The use of the word "always" should be avoided: even GoTo has its place, we just don't trust students to use it wisely. – user3079666 Apr 05 '22 at 12:10
  • @user3079666 Please interpret my (six year old) comment in context. Are you using a `for` loop to meet your (valid) usecase, like the question asker is doing? If no, then your response is targeting a strawman. If yes, then please use the right tool: a `while` loop. – Akshat Mahajan Apr 06 '22 at 13:31

4 Answers4

13

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

Community
  • 1
  • 1
en_Knight
  • 5,301
  • 2
  • 26
  • 46
  • thank you the while loop worked for me. Will read more about the iterator concept in python. – physicist Apr 15 '16 at 20:24
  • while it makes sense in the context of python, python doesn't make sense in the context of a for loop. By the time you write a for loop, it is both desirable and conventional to have this kind of control without reducing to the lower level while loop. However, in *scripting* languages, such as BASH, it is consistent. Is python a scripting language? I can compile it... – Chris Jul 20 '23 at 16:07
  • Yes, "why does this happen [what is the technical mechanism]" and "for what reason did the language authors program it to happen this way" are related questions, but I only answered the first one here. Python early on made the decision to use first-class objects where other languages wouldn't, and this often causes confusion for non-python natives (like default arguments in functions), myself included. In this case, it is "pythonic" for the iterator to be a first-class object with an "__in__" method, instead of a syntactic structure that gets expanded by a compiler, imo – en_Knight Jul 25 '23 at 14:30
  • I agree that python loops can be quirky! Another example: they don't establish scopes, like many other languages would – en_Knight Jul 25 '23 at 14:31
3

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
nathan.medz
  • 1,595
  • 11
  • 21
3

If you want to update an iterator, you can do something like that :

iterator= iter(range(100))
for i in iterator:
    print (i)
    for k in range(9): next(iterator)

But no practical interest !

B. M.
  • 18,243
  • 2
  • 35
  • 54
  • Huh I owe you an apology - the confusion is caused by this absolutely [baffling bug](https://snipboard.io/RFuVUX.jpg) in my Python 3.7 (provided by conda). Miraculously, this bug makes your otherwise correct code run incorrectly, and my unnecessary code run correctly! Sorry for the confusion, a bug this catastrophic is mind boggling to me – Anti Earth Nov 07 '22 at 17:33
  • Ahh solved - not a bug, but an extremely unintuitive interactive interpreter [behaviour](https://snipboard.io/9jPVlL.jpg) of `iter` whereby every return value of `next()` is printed (unless like in my example, assigned to a variable). How awful, sorry again! – Anti Earth Nov 07 '22 at 17:40
0

If you try this code it should work.

for i in range(100)[::10]:
    print i

The [::10] works like string slicing. [first position to start at: position to stop at:number to steps to make in each loop]

I didn't use the first two values so these are set to the default of first position and last position. I just told it to make steps of 10.