Changing python list size during iteration. Is it okay?

80
April 06, 2022, at 11:20 AM
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?

Answer 1

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
READ ALSO
Average using loops

Average using loops

Anyone know how to rearrange this code so that when the values that are inputted are 3 4 8 4 , the average is 475

54
I think it&#39;s a basic question but I don&#39;t get why I get 0 in this function

I think it's a basic question but I don't get why I get 0 in this function

I'm wondering why I get 0 for the print(a) call in the last lineI put 0 for the first loop of the add()function and it should return 1 and so on in the for loop

74
Python variable won&#39;t update outside of module

Python variable won't update outside of module

I have a variable called store_number that I pass in from my mainpy into a module called store_selector which increments the store number until it finds a valid store

73