Control the index of a Python for loop

for-loop, python

Solution

How do you control the index of a python for loop? (or can you? or should you?)

You can't / shouldn't - the loop control variable will be reassigned at the end of each iteration to the next element of whatever it is you are iterating over (so that `i = i + 1` has no effect, since `i` will be reassigned to something different for the next iteration anyway). If you want to control the index like that, you should use a `while`-loop:

i = 0
while i < 10:
    print i
    i = i + 1

Although, Python's `range` function is more flexible than you might realize. For instance, to iterate in steps of 2 you can simply use something like

for i in range(0, 10, 2):
    print i

Problem

How do you control the index of a python for loop? (or can you? or should you?) For Example: ``` for i in range(10): print i i = i + 1 ``` Yields: ``` 0 1 2 3 4 5 6 7 8 9 ``` I want it to yield: ``` 0 2 3 4 5 6 7 8 9 10 ``` I really do apologize if I'm just completely off track with this question, and my brain is completely failing me at the moment and the solution is obvious. Why am I asking? This is irrelevant to the question, but relevant to the why I need the answer. In a Python script I'm writing, I am doing something like this: ``` for i in persons: for j in persons[-1(len(persons) - i - 1:]: if j.name in i.name: #remove j.name else: #remove i.name #For every person (i), iterate trough every other person (j) after person (i) #The reason I ask this question is because sometimes I will remove person i. #When that happens, the index still increases and jumps over the person after i #So I want to decrement the index so I don't skip over that person. ``` Maybe I am going about this completely the wrong way, maybe I should use a while loop and control my indices.

Original source

Related problems