For Loop Not Working How I expected

I was solving Python Code challenges: Loops-Question 3 ( 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:
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.

Your assistance would be appreciated!

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:
return lst

gotcha, thanks for that!

1 Like