27
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.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
ilaunchpad
  • 1,283
  • 3
  • 16
  • 32
  • 2
    possible duplicate of [How to change index of for loop in Python?](http://stackoverflow.com/questions/14785495/how-to-change-index-of-for-loop-in-python) – 101 Aug 28 '15 at 21:43

7 Answers7

21

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
Matt Anderson
  • 19,311
  • 11
  • 41
  • 57
  • 5
    This is not very helpful when OP wants to increase the variable more that 1. And actually there is no need to make the task sophisticate like that when we can simply use a `while` loop. – Mazdak Aug 28 '15 at 21:51
  • @Kasramvd - this is the general pattern when working with iterators. It can be any iterator, not just a sequence of numbers increasing by 1. If you want to advance the iterator by more than one position, call `next()` more than once. If you really want to work with and manipulate index numbers directly like a c for-loop, then one shouldn't use iterators but instead another approach (agreed). – Matt Anderson Aug 28 '15 at 23:00
  • 1
    This method does not work when one wants to iteratore over a list. – Kev1n91 Jan 02 '17 at 10:57
17

You can't do this inside a for loop, because every time the loop is restarted it reassigns the variable i regardless of your changes on the variable.

To be able to manipulate your loop counting variable, a good way is 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
...

Additionally, if you want to increase the variable on a period rather than based on some particular condition, you can use a proper slicers to slice the iterable on 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]).

Mazdak
  • 105,000
  • 18
  • 159
  • 188
3

range() has an optional third parameter to specify the step. Use that to increment the counter by two. For example:

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

The reason that you cannot increment i like a normal variable is because when the for-loop starts to execute, a list (or a range object in Python 3+) is created, and i merely represents each value in that object incrementally.

pzp
  • 6,249
  • 1
  • 26
  • 38
  • This answer is good only for fixed increment since it will increment every time, not a solution for conditional increment. – Ubaid Qureshi Oct 07 '21 at 17:31
1

@ilaunchpad Sorry I know it's too late to post this but here is what you were looking for

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

You should not use the same variable throughout in the For statement.

Output
vaibhav@vaibhav-Lenovo-G570:~$ python3 /home/vaibhav/Desktop/Python/pattern_test.py
0
2
4
6
8
10
12
14
16
18
increased i 20
user7422128
  • 902
  • 4
  • 17
  • 41
1

How about this?

for i in range(10):
     if i == 3:
         i += 1
         continue
     print(i)

Just adding the continue makes the counter go up - the print result is:

0
1
2
4
5
6
7
8
9

Note that without the continue, the 4 will be printed twice. I think this answers the question.

Grayrigel
  • 3,474
  • 5
  • 14
  • 32
JSD
  • 11
  • 1
  • Thank you for editing. When I originally wrote the answer, it looked fine to me - the code was not in the text and there is no obvious way to add code. I think that replacing my think/hope with think only sort of takes away the modesty that I wanted to put in the answer. I used this idea in my own code and it does work and it is extremely simple. – JSD Oct 18 '20 at 04:33
0

I wrote something like this.

    while True:
        if l < 5:
            print "l in while", l
            l += 1
        else:
            break

Now I am having a full control but the backdrop is that I have to check all the conditions.

GustavoIP
  • 873
  • 2
  • 8
  • 25
Baradwaj Aryasomayajula
  • 1,184
  • 1
  • 16
  • 42
0

As there are no answers that allow to use the result of the next iterator, here is my proposed solution, that works with many lists and iterables by using either the enumerate() function or just the iter() function:

x = [1, True, 3, '4', 5.05, 6, 7, 8, 9, 10]
x_enum = enumerate(x)
for idx, elem in x_enum:
    if idx == 1: # Example condition to catch the element, where we want to iterate manually
        print('$: {}'.format(elem))
        idx, elem = next(x_enum)
        print('$: {}'.format(elem))
    else:
        print(elem)

will print:

1
$: True        # As you can see, we are in the if block
$: 3           # This is the second print statement, which uses the result of next()
4
5.05
6
7
8
9
10

This is also possible with a simple iterator:

x_iter = iter(x)
for elem in x_iter:
    if elem == '4': # Example condition to catch the element, where we want to iterate manually
        print('$: {}'.format(elem))
        elem = next(x_iter)
        print('$: {}'.format(elem))
    else:
        print(elem)
R. Joiny
  • 309
  • 7
  • 17