def delete_starting_evens(lst): for i in lst: if i%2==0: lst.pop(0) else: break return lst print(delete_starting_evens([4, 8, 10]))
It’s caused by altering the list you’re iterating through. Try having a look at the value of
i with print or something whilst you step through your loop.
Please avoid posting in multiple locations.
I didn’t understand what you mean. All the elements in the list are removed, which shows that I have put the if statement correctly. But I have no idea why 10 is left. Can you please point out what made this to happen?
Are they? I’d suggest you throw in some
Removing elements from the list you are looping over is a recipe for disaster.
Lets do your list as example, with the indexes/positions below:
4 8 10 0 1 2
the moment you remove element/value
4 of the list we get:
_ 8 10 0 1 2
the underscore represents the lack of a value. But a list can not exists like this. So everything shifts, everything to the right of the removed element moves to left, resulting in:
8 10 0 1
but the loop moves on to next index/position (the loop was at index 0, moves to index 1)
then 8 is removed, so our new list looks like this:
the loop moves on to the next index/position (2), but there is nothing there, so the loop is done
Thanks for explaining. I literaly created a mess. It helped me to correct the program.
def delete_starting_evens(lst): for j in range(len(lst)): list_length = len(lst) for i in lst: if i % 2 == 0: lst.pop(0) print(lst) break return lst print(delete_starting_evens([4, 8, 10]))
This worked. Thanks again
That is quite a mess and not very readable/easy to understand.
Maybe should choice a different approach?