a = [1,2,3,4,5]
for i in range(len(a)):
a.pop(0)
print ('%d/%d' % (i, len(a)))
Above is simple code changes list size during iterating itself.
$ python test.py
0/4
1/3
2/2
3/1
4/0
And the result was like above.
From 2/2, i exceed the total iteration size!
Question
Could anyone tell me why the code still executes after exceeding the size?
hmm... for easier explanation, what happened here is
when you run for i in range(len(a)):
it will automatically run for i in range(5):
so it will not call the len function again and again for each loop
This is another example:
length=5
for i in range(length):
length=2
print(length)
the result is
2
2
2
2
2
Correct me if I am wrong, but I think most of for iteration (any language) is fixed since beginning, if you want to loop something that is not fixed, better use while
length=5
i=0
while i < length:
length=2
print(length)
i+=1
The result
2
2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With