Python-code-challenges-loops

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

https://www.codecademy.com/courses/learn-python-3/articles/python-code-challenges-loops

This is because you’re breaking the entire loop if the number is odd.

So, if you have a list such as [1,2,3] the first number is odd, the list would immediately break without removing any of the evens.

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.

Hope that helps

1 Like

Thanks so much! I get it now. I thought that the loop would re-check the loop on every time, but this isn’t the case.

1 Like

I am aware of that, but the example lists provided started with an even number so I wasn’t worrying about it.

1 Like