Delete_starting_evens

Hi all. I see the solution which makes sense to me, but I can’t figure out why my initial approach below does not work. Any help would be much appreciated. Thanks!!

#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]))

If we mutate the list we are iterating, it throws our iteration sequence afoul.

Try using a slice to iterate, and then mutate the original as a side effect. This will have no effect on the iteration.

for num in lst[:]:
    if num % 2 == 0:
        lst.remove(num)
...

Of course the elephant in the room here is that ALL the evens get removed, not just those at the start. Something to consider in your re-evaluation of the solution.

Hint, there should be an else, but not to continue, rather exit the function with list in tow. The final return (after the loop) would be an empty list, since it has been emptied of its contents.

for ...:
    if ...:
        ...
    else:
        break
return lst

Proof of concept:

>>> def drop_starting_evens(lst):
...     for num in lst[:]:
...         if num % 2 == 0:
...             lst.remove(num)
...         else:
...             break
...     return lst
... 
>>> drop_starting_evens([4, 8, 10, 11, 12, 15])
[11, 12, 15]
>>> 

Note that we preserved the even number after the odd one.

For a better look at where this is all going, let’s take a sneak peak at what is unfolding…

>>> def drop_while(f, lst):
...     def even(x):
...         return not(x & 1)
...     def odd(x):
...         return not(even(x))
...     for num in lst[:]:
...         if f(num):
...             lst.remove(num)
...         else:
...             break
...     return lst
... 
>>> drop_while(even, [4, 8, 10, 11, 12, 15])
[11, 12, 15]
>>> drop_while(odd, [1, 3, 5, 7, 9, 10, 11, 12])
[10, 11, 12]
>>> 

In point of fact, the embedded functions are not needed since Python already has them in the Standard Library.

We can extend the Standard Library with functions of our own in the global namespace:

>>> def is_number(x):
...     return isinstance(x, int) or isinstance(x, float)
... 
>>> def drop_while(f, s):
...     for e in s[:]:
...         if f(e):
...             s.remove(e)
...         else:
...             break
...     return s
... 
>>> drop_while(is_number, [1, 3, 5, True, False, '10', 11, 12])
['10', 11, 12]
>>>