Why is this not working as an alternate method to remove positive numbers from beginning of list?

trying to do: python code challenges: loops (challenge number 3)
I know that the way I am trying to code this is different than the solution than they are giving, but I still wanted to try and get it to work.
This is what I have so far:

#Write your function here
def delete_starting_evens(lst):
  for num in lst:
    if num % 2 == 0:
      lst.remove(num)
    else: break
  return lst
    
#Uncomment the lines below when your function is done
print(delete_starting_evens([4, 8, 10, 11, 12, 15]))
print(delete_starting_evens([4, 8, 10]))

when I run this code, the output is [8, 11, 15], and [8], and I really for the life of me cannot figure out what is going on here.

You’ll read this often: alter a list while iterating (with for) at one’s own peril.

3 Likes

Hi there,

If you have a program like PyCharm or any other debugger you can probably step into your code to help see what is going on at any given moment. I’m sure there are some online debuggers as well.

You could, alternatively throw in some print statements when you try to understand what’s going on. For example:

def delete_starting_evens(lst):
    for num in lst:
        if num % 2 == 0:
            print(num, end= ' ')
            lst.remove(num)
    print()
    return lst

will give:

4 10 12 
[8, 11, 15]

The problem is. The for-loop starts searching first at lst[0], then lst[1], then lst[2], etc. Only, when you remove the item from the list, the length of the list changes and so do the items at that given index.
So when for example the number 4 was removed, your for loop moves towards lst[1] which is that point the number 10. When you remove the number 10 at lst[1], your for loop moves to lst[2] which is now the number 12.

Hope that helps!

To repeat, only remove from a list if iterating in reverse with for. .remove() is the totally the wrong tool for this job.