Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing python list size during iteration. Is it okay?

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?

like image 716
Jiwon Avatar asked Apr 19 '26 11:04

Jiwon


1 Answers

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
like image 118
d_frEak Avatar answered Apr 21 '26 00:04

d_frEak