# For Loop Not Working How I expected

Hi,
I was solving Python Code challenges: Loops-Question 3 (https://www.codecademy.com/courses/learn-python-3/articles/python-code-challenges-loops) and I’m confused as to why my code isn’t working.

This is the prompt:

1. Define our function to accept a single input parameter `lst` which is a list of numbers
2. Loop through every number in the list if there are still numbers in the list and if we haven’t hit an odd number yet
3. Within the loop, if the first number in the list is even, then remove the first number of the list
4. Once we hit an odd number or we run out of numbers, return the modified list

And this is my code:
def delete_starting_evens(lst):
for n in lst:
if lst[0] % 2 == 0:
lst.remove(lst[0])
else:
break
return lst

It works for print(delete_starting_evens([4, 8, 10, 11, 12, 15]))

However, for print(delete_starting_evens([4, 8, 10])), it returns [10], instead of an empty list.

Mutating a list that is being iterated will have consequences. Not a good idea.

The trick is to iterate a copy of the list, then we can mutate the main list without affecting iteration.

``````for x in lst[:]:
if x % 2 == 0:
lst.remove[x]
else:
break
return lst
``````
3 Likes

gotcha, thanks for that!

1 Like