Hey everyone!
I’m wondering if anyone can tell me what I’m doing wrong in the third exercise on Python Code Challenges Loops (Not the advanced). I know there is a solution included but I don’t understand why my code isn’t working. Can anyone help me?
Here is my code:
def delete_starting_evens(lst):
for num in lst:
if num % 2 == 0:
lst.remove(num)
elif num % 2 == 1:
break
return lst
Hi,
You’re changing the list that you’re iterating through (something you should try and avoid as it tends to be unpredictable).
So, if you delete the first item in the list, the second item then becomes the first.
It then loops back round, moves to what is now the second item, and you’ve missed one out.
e.g
[2,4,6,7]
Your code would remove the 2, but on the second loop the list would be;
[4,6,7]
however num would equal 6, not 4.
You want a loop that will continue while the first element is even.