Unexpected behavior with a list in a for loop

Hello,

When I execute the function below with the following arguments : print(delete_starting_evens([4, 8, 10])) I get [10] instead of the expected []. Why isn’t 10 getting popped? It is even, and it is at index 0 in the list at the time it is reached in the for loop.

Thanks!

def delete_starting_evens(lst):
  for element in lst:
    if lst[0] % 2 == 0:
      lst.pop(0)
    else:
      break
  return lst

In case you’re curious this is from Python Code Challenges: Loops, exercise 3 in the Learn Python 3 course.

https://www.codecademy.com/courses/learn-python-3/articles/python-code-challenges-loops

It’s an unfortunate common gotcha in Python. If you’re iterating through an objects and changing the length of that object at the same time you’ll run into all sorts of weird behaviour that’s hard to keep track of.

You’ll probably want to rearrange your code to avoid this.

2 Likes