简体   繁体   中英

for loop does not run till the end index of the list

Below code runs for two times only. No idea why it is happening.

a=[1,2,3,4]
count=0
for letter in a:
    print(letter)
    b=a.pop()

    count+=1
print("total loop count is "+str(count))

I expect that the loop should run for four times. If I comment / remove line b=a.pop() , then the loop runs for four times.

I expect print for the count after the program exit loop should be four, but actual output print for the count is 2.

The list.pop() method without a parameter removes the last item of the list. Check out the documentation .

So basically what happens is:

  • Loop 1 (letter is 1, 4 is removed)
  • Loop 2 (letter is 2, 3 is removed)
  • No loop 3 since the list a has no more elements.

Generally it is considered bad practice to modify a collection when iterating on its elements. Doing so often results in unintended behavior.

1st step: print the first element, remove the 4th one

2nd step: print the second element, removes the 3rd one

... no elements left to print.

Because you change the element size of the iterator a using the line:

b=a.pop()

every time running the line, the list a will remove its last element and the size of it will be reduced by 1.

the simplest way to get your expection is to make the iterator unchangeable at line 3 for letter in a[:] :

a=[1,2,3,4]
count=0
for letter in a[:]:
    print(letter)
    b=a.pop()

    count+=1
print("total loop count is "+str(count))

and the output will be correct:

1
2
3
4
total loop count is 4

a little improved code

a=[1,2,3,4]
count=0
while len(a)>0:
    count+=1
    print(a[-1])
    a.pop()

print("total loop count is {}".format(count))

Just to understand the concept. Use enumerate() to know the count of the iteration, When the pop is called for the second time the len(a) becomes 2(which means there is no 3rd item to print for the third iteration). run below code once to get a better idea. It is sot recommended to pop or remove from the list inside for loop.

count=0
for iteration_count,letter in enumerate(a):
    print("Index Value:",iteration_count)
    b=a.pop()
    print("Length of a:",len(a))
    count+=1
print("total loop count is "+str(count))

While the below code would help you if you want to pop all the items.

count=0
while a:
    a.pop()
    print(a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM