Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing iteration variable inside for loop in Python [duplicate]

Tags:

python

I am trying to do something as simple as changing the varible in which I am iterating over (i) but I am getting different behaviours in both Python and C.

In Python,

for i in range(10):     print i,     if i == 2:         i = 4; 

I get 0 1 2 3 4 5 6 7 8 9, but the equivalent in C:

int i; for (i = 0; i < 10; i++) {     printf("%d", i);     if (i == 2)         i = 4; } 

I get 01256789 (note that numbers 3 and 4 don't appear, as expected).

What's happening here?

like image 652
nunos Avatar asked Apr 09 '13 13:04

nunos


People also ask

How do you change a variable value in a loop in Python?

If you put i = 4 then you change i within the step of the current iteration. After the second iteration it goes on as expected with 3. If you wnat a different behaviour don't use range instead use a while loop. If you are using a for loop, you probably shouldn't change the index in multiple places like that.

How do you repeat iterations in Python?

The Python for statement iterates over the members of a sequence in order, executing the block each time. Contrast the for statement with the ''while'' loop, used when a condition needs to be checked each iteration or to repeat a block of code forever. For example: For loop from 0 to 2, therefore running 3 times.

Can we change I in for loop Python?

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.

How do you change iterable in Python?

Python iter() is an inbuilt function that is used to convert an iterable to an iterator. It offers another way to iterate the container i.e access its elements. iter() uses next() for obtaining values. The iter() method returns the iterator for the provided object.


1 Answers

Python has a few nice things happening in the background of for loops. For example:

for i in range(10): 

will constantly set i to be the next element in the range 0-10 no matter what.

If you want to do the equivalent in python you would do:

i = 0 while i < 10:     print(i)     if i == 2:         i = 4     else:      # these line are         i += 1 # the correct way     i += 1 # note that this is wrong if you want 1,2,4,5,6,7,8,9 

If you are trying to convert it to C then you have to remember that the i++ in the for loop will always add to the i.

like image 114
Serdalis Avatar answered Oct 12 '22 11:10

Serdalis