简体   繁体   中英

Why doesn't the pop method break the while-loop in this example?

Expected Outcome: while loop will break when z = []

Actual Outcome: Index Error. Loop does not break even after pop method "empties" the list.

Index error at "front_of_list = z[0]" because at that point, z = []

Example code:

z = [6,3,7,4,9,7,8,4,5,7]
while z:
    front_of_list = z[0]
    if z[0] == 7:
        print("SEVEN!")
        popped = z.pop(0)
    front_of_list = z[0]
    print(front_of_list)
    popped = z.pop(0)

If you see properly and print the output:

z = [6,3,7,4,9,7,8,4,5,7]
while z:
    front_of_list = z[0]
    if z[0] == 7:
        print("SEVEN!")
        popped = z.pop(0)
    front_of_list = z[0]
    print(front_of_list)
    popped = z.pop(0)
    print(z)

This is what you get:

6
[3, 7, 4, 9, 7, 8, 4, 5, 7]
3
[7, 4, 9, 7, 8, 4, 5, 7]
SEVEN!
4
[9, 7, 8, 4, 5, 7]
9
[7, 8, 4, 5, 7]
SEVEN!
8
[4, 5, 7]
4
[5, 7]
5
[7]
SEVEN!
Traceback (most recent call last):
  File "/.../your file", line 7, in <module>
    front_of_list = z[0]
IndexError: list index out of range

Your while loop doesn't catch that because you pop the element in the if statement but you also pop the element outside it.

front_of_list = z[0]
print(front_of_list)
popped = z.pop(0)
print(z)

So before the iteration has completed, you pop the element. Your last element is 7 and you pop that in your if statement. Now the list is empty. But you try to pop it again outside the if statement. That is the error.

Example of last iteration:

while z:
    front_of_list = z[0] #=== last element is 7
    if z[0] == 7:
        print("SEVEN!") #=== Yes
        popped = z.pop(0) #=== 7 is removed from the list. So list is []
    front_of_list = z[0] #=== No element is in the list so you cannot index it. Hence an IndexError
    print(front_of_list)
    popped = z.pop(0)
    print(z)

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