Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change index of a for loop?

Suppose I have a for loop:

for i in range(1,10):     if i is 5:         i = 7 

I want to change i if it meets certain condition. I tried this but didn't work. How do I go about it?

like image 982
drum Avatar asked Feb 09 '13 06:02

drum


People also ask

Can I change the loop index variable within a for loop?

Changing len inside the loop will not help, since range for i variable is determined before the for-loop started and cannot be changed on run time. In other words, once the for-loop started, it forgets what is len , it just remembers that i has to be changed from 1 to 3.

Can I change the i in a for loop Java?

Yes the value of i will be changed but it becomes 8 ,not 7 . Because when i = 1 , then the condition i%2==0 doesn't satisfy and the if statement will be terminated without performing the addition. Then the value of i increment by 1 .

What is the index in a for loop?

The index value represents the number of the currently executing iteration. More specifically, the body of the loop (the instructions that are executed during each loop repetition) can be said to be iterated as the loop executes.


2 Answers

For your particular example, this will work:

for i in range(1, 10):     if i in (5, 6):         continue 

However, you would probably be better off with a while loop:

i = 1 while i < 10:     if i == 5:         i = 7     # other code     i += 1 

A for loop assigns a variable (in this case i) to the next element in the list/iterable at the start of each iteration. This means that no matter what you do inside the loop, i will become the next element. The while loop has no such restriction.

like image 82
Volatility Avatar answered Oct 08 '22 06:10

Volatility


A little more background on why the loop in the question does not work as expected.

A loop

for i in iterable:      # some code with i 

is basically a shorthand for

iterator = iter(iterable) while True:     try:         i = next(iterator)                 except StopIteration:         break     # some code with i 

So the for loop extracts values from an iterator constructed from the iterable one by one and automatically recognizes when that iterator is exhausted and stops.

As you can see, in each iteration of the while loop i is reassigned, therefore the value of i will be overridden regardless of any other reassignments you issue in the # some code with i part.

For this reason, for loops in Python are not suited for permanent changes to the loop variable and you should resort to a while loop instead, as has already been demonstrated in Volatility's answer.

like image 22
timgeb Avatar answered Oct 08 '22 06:10

timgeb