简体   繁体   中英

Why does the for loop behave differently than the while loop for the “pop” function?

I have the following list:

list1=['pic1','pic2', 'pic3']

The loop below iterates through the list:

n=0
for item in list1:
    nose= list1.pop(n)
    print(nose)

Output:

pic1
pic2

Why doesn't the last item in the list get printed in the for loop, but the while loop prints all three items:

n=0
while len(list1)>0:
    nose= list1.pop(n)
    print(nose)

Output:

pic1
pic2
pic3

You can test the first program to see what it's doing with a print statement:

list1=['pic1','pic2', 'pic3']
    n=0
    for item in list1:
        nose= list1.pop(n)
        print(f'{list1}, item={item}, popped={nose}')

First time through the loop, item contains pic1 , the value at index 0, it pops it and prints it:

['pic2', 'pic3'], item=pic1, popped=pic1

Second time through the loop, it prints:

['pic3'], item=pic3, popped=pic2

That is, it moved the index of the loop to position 1, which is now pic3 as you already popped an entry from the list on the previous iteration. It pops the pic2 from the list.

Now the loop is finished. The index of the next item is beyond the end of the list, so it stops.

As has been said in the comments, the basic rule is to never modify a list that you're iterating over, as it can have complex and unexpected (to the developer) results.

I observe that in below code you are always passing index 0 for pop() method.

list1.pop(n) where n=0

If you don't pass index to pop() then it will remove the last element in the list.

Syntax

**list.pop(pos)**

pos => Optional. A number specifying the position of the element you want to remove, default value is -1,which returns the last item .

In while loop, since you are passing 0 index to pop() method it will always remove items at 0 index and lenth of the list is 3 so it will print all three items.

for item in list1:
    nose= list1.pop()
    print(nose)


while len(list1)>0:
    nose= list1.pop()
    print(nose)

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