Loops code challenge, exercise 3

Hi all. I’m trying to figure out the difference between the code I wrote (that passed the checker) and the solution code for exercise 3 in the loops code challenge and am having some difficulty with it. Grateful to anyone who can explain why the solution code is the correct/better method! Thank you!

My code:

def delete_starting_evens(lst): for num in lst: if (len(lst) > 0) and (lst[0] % 2 == 0): lst = lst[1:] return lst

Solution code:

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

Hey there and welcome to the Codecademy forums!! :slightly_smiling_face:

First off I would like to say the solution code isn’t always the “better” solution, but often just a solution.
In your case, you could argue the solution code is more efficient than yours since it use a while loop as opposed to a for loop. For example if we give each function a list:

[2, 4, 3, 5, 7, 9, 11]

Your for loop will loop through every number in the list, as opposed to the solutions while loop which will terminate as soon as it finds an odd number. Less loops means less run time, which can be important when working with lots of data.

You could fix this with a break but the while loop is a lot more compact and easier to read.

1 Like

Ah gotcha, thank you for explaining!