I am trying to solve the exercise at the following link:
It is required to build a function that removes all the even numbers at the beginning of a list.
[4, 8, 10, 11, 12, 15]
[4, 8, 10]
in these two cases the code should return, respectively:
[11, 12, 15]
The solution provided is the following:
def delete_starting_evens(lst): while len(lst) >= 1 and lst%2 == 0: lst = lst[1:] return lst
I have two questions:
- If I swap the two conditions connected by
and, the interpreter throws an error (list index out of range). This happens only for the second list (where all numbers are even).
(i.e. I get an error if I use the following code):
def delete_starting_evens(lst): while lst%2 == 0 and len(lst) >= 1: lst = lst[1:] return lst
Why does this happen? Should not the two conditions be applied at the same time, whatever the order in which they are written?
- In my opinion, the code
lst = lst[1:]should throw an error when the loop is operating with the second list.
In fact, after the elements 4 and 8 are removed in the first two iterations, the list becomes
lst = , and applying the slicing command
[1:]on this list means referring to the index 1 of the list. But this list does not have an index 1, it only has index 0.
Why don’t I get any error?
Thank you very much in advance, this problem kept me awake for several hours last night!