Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to increment the iterator from inside for loop in python 3?

Tags:

for i in range (0, 81):     output = send command     while True:         last_byte = last_byte - offset     if last_byte > offset:        output = send command        i+     else:         output = send command         i+         break 

I want to increase the iterator every time the send command is executed. Right now it only increases by one when the for loop is executed. Please advise

for i in range(0,10):     print(i)     i +=2     print("increased i", i) 

I ran this code and it produced out from 0 to 9. I was expecting it would increase the iterator by 2.

like image 603
ilaunchpad Avatar asked Aug 28 '15 21:08

ilaunchpad


People also ask

How do you increment inside a for loop?

A for loop doesn't increment anything. Your code used in the for statement does. It's entirely up to you how/if/where/when you want to modify i or any other variable for that matter.

How do you increase the step size in a for loop in Python?

To iterate through an iterable in steps, using for loop, you can use range() function. range() function allows to increment the “loop index” in required amount of steps.


2 Answers

Save a copy of the iterator as a named object. Then you can skip ahead if you want to.

>>> myiter = iter(range(0, 10)) >>> for i in myiter:     print(i)     next(myiter, None) ... 0 2 4 6 8 
like image 176
Matt Anderson Avatar answered Oct 24 '22 19:10

Matt Anderson


You can't do that inside a for loop. Because every time that the loop gets restarted it reassign the variable i (even after you change it inside the loop) and every time you just increase the reassigned variable. If you want to do such thing you better to use a while loop and increase the throwaway variable manually.

>>> i=0 >>> while i< 10 : ...     print(i) ...     i +=2 ...     print("increased i", i) ...  0 ('increased i', 2) 2 ('increased i', 4) 4 ('increased i', 6) 6 ('increased i', 8) 8 ('increased i', 10) 

Beside that, if you want to increase the variable on a period rather than based some particular condition, you can use a proper slicers to slice the iterable in which you're looping over.

For instance if you have an iterator you can use itertools.islice() if you have a list you can simply use steps while indexing (my_list[start:end:step]).

like image 32
Mazdak Avatar answered Oct 24 '22 18:10

Mazdak