dv151
dv151

Reputation: 115

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)

Upvotes: 0

Views: 286

Answers (1)

user15801675
user15801675

Reputation:

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)

Upvotes: 2

Related Questions