Python Code Challenges: Loops - 3. Delete Starting Even Numbers

Hello
I am having issues with https://www.codecademy.com/paths/computer-science/tracks/cspath-cs-101/modules/cspath-code-challenges/articles/python-code-challenges-loops

def delete_starting_evens(lst):

  # new_list = lst

  for index in range(len(lst)):

    while lst[index] % 2 == 0 and len(lst) > 0:

      lst.pop(index)

    return lst


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

The program works for the first list but fails as soon as I have a list that only has even numbers. I get "IndexError: list index out of range"
If I change the condition to len(lst) > 1" it returns the list [10], but I fail to delete the last item with this method and the logic escapes me.

I have edited the initial conditions in the while loop to check if len(lst) > 0 first, and now it works.
I thought the two conditions must both be true

Python uses a little trick here, in more generic terms this is the condition you have:

A and B: 

when A is false, there is no way this condition can become true. So python doesn’t even evaluate B.

this is why you get away with:

while len(lst) > 0 and lst[index] % 2 == 0:

if there no elements in the list, the left side evaluate to false and the right side doesn’t evaluate

2 Likes

I just noticed that, but I don’t understand why there is a difference.
If both A and B are not true, it shouldn’t continue the loop as far as I understand.

Thanks a lot for the reply!

The moment A is false, python doesn’t even evaluate B. The right hand side (B) is then completely ignored (this goes for AND operator, doesn’t apply to OR operator). I suppose this gains some performance? given now only condition is evaluated.

so if there no elements in the list and you do this check:

len(lst) > 0

everything thing is fine, but this:

lst[index] % 2 == 0

is a problem when there no elements in the list

3 Likes

Ah, so it is the first condition in itself that is causing the error, not the body of the loop.
Python can’t evaluate the first condition because of an index out of range - it can’t assign True or False and I get an error.

Thanks a lot, that was really helpful

Calling .pop() on an empty list would also cause an error. But the code doesn’t get there. Because there is an error/mistake earlier.

Looking up an index which does not exists in a list results in an error.

1 Like

What is really interesting is that even in the official solution the same issue arises:
If we are to switch the two conditions we get the same error.

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

Works

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

Returns the same error.

that should make sense at this point? :slight_smile:

1 Like

It does, yes. It was just exemplifying the point even better.

1 Like