Unfortunately, the indexer in for
loop Python
will be assigned every time it iterates to the new item. Thus, your one time reassignment:
if i == 15:
i = 5
won't help much in the subsequent iteration
From the Python for statement documentation:
The expression list is evaluated once; it should yield an iterable
object. An iterator is created for the result of the expression_list.
The suite is then executed once for each item provided by the
iterator, in the order of ascending indices. Each item in turn is
assigned to the target list using the standard rules for assignments,
and then the suite is executed. When the items are exhausted (which is
immediately when the sequence is empty), the suite in the else clause,
if present, is executed, and the loop terminates.
In other words, for your item
i
, no matter what happen in the loop would be reassigned with the next value provided in the iterable object
, in your case being set generated by range(20)
#at loop 15
[0 1 2 ... 15 16 19] #i is progressively increasing independent from what happen in the loop block
^ #here is i
change i to 5? you can, but only lasting for one loop!
#you print i, it shows 5, and then...
#at loop 16
[0 1 2 ... 15 16 19]
^ #still got reassigned at the beginning of the next loop
One way is to create another indexer - independent from the for
loop which is reset when your for
loop indexer i
reaches 15
:
j = 0
for i in range(20):
if i == 15:
j = 5;
print(j)
j = j + 1
Another way, not so recommended, is to reassign i
every time after i >= 15
(you choose to fight with the basic indexer re-assignment everytime)
for i in range(20):
if i >= 15:
i = i - 10;
print(i)