Python 3 Delete Starting Even Numbers

Hello, I wrote the code:

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

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

but it returns the error:

[11, 12, 15]
Traceback (most recent call last):
  File "script.py", line 11, in <module>
    print(delete_starting_evens([4, 8, 10]))
  File "script.py", line 3, in delete_starting_evens
    while (lst[0] % 2 == 0 and len(lst) > 0):
IndexError: list index out of range

However when I switch the order of the and statements to:

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

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

it returns

[11, 12, 15]
[]

Why does the and statement work one way and not the other?
Can someone please explain why this is happening? Thanks.

On the final loop with an empty list, the first example is asked to look at index 0 of an empty list and that doesn’t exist.
With the conditions are reversed it finds that len(lst) > 0 == False and ends the loop without checking lst[0].

Disclaimer: I’m just a fellow student

1 Like

Makes sense thank you!