 Help with "Delete Starting Even Numbers" exercise

This exercise wants us to:

" …remove elements from the front of lst until the front of the list is not even. The function should then return lst .

For example if lst started as [4, 8, 10, 11, 12, 15] , then delete_starting_evens(lst) should return [11, 12, 15] ."

At first, I tried using a for loop until I learned that modifying the list while iterating through it caused a lot of issues. I saw others use while loops in their solutions so that’s what I tried using. Running my code returns an error saying that the ‘lst[index] is out of range’, but I do not understand why?

#Write your function here def delete_starting_evens(lst): length = len(lst) index = 0 while index<length: if lst[index] % 2 == 0: lst.remove(lst[index]) index += 1 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]))

For the same reason you mention, I think the bit you missed is that length is only calculated once.

However even if you do correct for the length you should also consider what will happen if you remove an element, if your index used to refer to the third element of the original list what does it now refer to? Could this also be a problem?

If there is one thing I’ve learned from this challenge it is to not refer to a list’s index while trying to modify the list. Codecademy’s solution is:

def delete_starting_evens(lst): while (len(lst) > 0 and lst % 2 == 0): lst = lst[1:] return lst

I understand the conditions for the while loop, but I do not understand the indented part within the while loop. It is my understanding that lst will be the same except it starts at the first index? How does this not just return a list that removes only the zero index?

1 Like

Heh, that’s a worthwhile thing to know, it crops up surprisingly often (even from folks who should know better ). Whilst you can try to do so it’s hard to keep track of which means that even a working solution might be a problem as the next person might not understand it.

In the code you’ve shown each time you use the slice notation like lst[:] you create new list (a shallow copy, the list is new but the objects it refers to are unchanged). If you consider the fact this slicing operation is in a loop then you might be able to work out how it works; the condition is important.

1 Like

So a new list that starts at the first index of the previous is being created and run through the loop until one of the conditions is not met?

Sounds about right, worth you doing a quick test just for a sanity check.

Try something like the following if it helps (change or modify it to add any bits you’re unsure about)-

lst = list("abcdefg") print(f"Start: {lst}") while (len(lst) != 0): lst = lst[1:] print(lst)
1 Like