# Need an explanation for a solution as I am struggling to grasp the concept

Hi am currently working my through the Python course.

I have just been working on a problem that got the better of me so I looked at the solution.

After breaking down the solution I am still struggling to understand why it works in one case and not the other.

It’s the Delete Starting Even Numbers challenge.

The function should 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]` .

Make sure your function works even if every element in the list is even!

The solution is this.

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

This is the inputs that were provided.

``````print(delete_starting_evens([4, 8, 10, 11, 12, 15]))

print(delete_starting_evens([4, 8, 10]))
``````

I understand how this works on the first set of inputs.

While the length of the list is greater than zero, and the list index position 0 can be divided by two with no remainder, the lst is then the lst from the next position. This then iterates through the loop again.

However I am unsure of why this works on the second set of inputs as both criteria are met so wouldn’t it surely output an empty list? I know this is not the case, however I am struggling to understand why?

Thanks,

Hello there!

``````print(delete_starting_evens([4, 8, 10]))
``````

The above code does return an empty list. What output are you getting?

3 Likes

I know the code works I just don’t understand why it works? I’m looking for an explanation if someone has one?

It does the same thing as when the code loops through the first list.
There are three items in the list:

1. When it loops through the list the first time, it checks to see if the length of the list is greater than 0. It is. Then it checks if the first element is even. Which it is. So, the loop deletes that item.
2. There are now two items in the list. It checks if the length of the list is greater than 0-which it is. It checks if the first item is even. Which it is. So, the loop deletes that.
3. There is now one item in the list. The loop checks to make sure the length of the list is greater than 0. Which it is. It checks if the first item is even. Which it is. So, the loop deletes that.
4. There are now no elements in the list-it’s length is 0. First, the loop checks to see if the length of the list is greater than 0. Which it isn’t. The loop is now over.

I hope this helps!

2 Likes

That explains it, thank you!

2 Likes