While loop condition question

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

Write a function that removes elements from the front of a list until the front of the list is not even. The function should then return list.

Why do we need to have len(lst) > 0 condition in the while statement.

Hello @java9059758472, I believe the reason for this is so that the code isn’t attempting to run on an empty list. So, if you have an empty list passed into the function, and that isn’t there:

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

Then this error appears:

Traceback (most recent call last):
  File "Main.py", line 7, in <module>
    print(delete_starting_evens([]))
  File "Main.py", line 4, in delete_starting_evens
    while (lst[0] % 2 == 0):
IndexError: list index out of range

This occurs because the loop is attempting to find the index 0 of an empty list, which has nothing in it, and therefore nothing to index.
The len(lst) > 0 is also there in case the list is all even numbers, in which case you should have an empty list returned. The length of an empty list is 0, so that condition stop the loop attempting to work on an empty list, similar to the above reason.

The same error occurs if you have the conditions the other way around:

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

This happens because Python evaluates from left to right, so it reaches the first condition (lst[0] % 2 == 0), and, in the case of an empty list, finds nothing at that index (index is out of range), so it raises that error.

I hope this helps!

1 Like