I was trying to create a simple function that, given a list, removes the first entry until until an odd number is indexed at 0
.
For example, the function would return the list [4, 8, 10, 11, 12, 15]
as [11, 12, 15]
.
This is the code I wrote initially:
def delete_starting_evens(lst):
while lst[0]%2==0 and len(lst)>0:
lst=lst[1:]
return lst
print(delete_starting_evens([4, 8, 10, 11, 12, 15]))
print(delete_starting_evens([4, 8, 10]))
If I run this code I get IndexError: list index out of range
caused by the final print statement.
However, if I switch the conditions around the and
statement as follows:
def delete_starting_evens(lst):
while len(lst)>0 and lst[0]%2==0:
lst=lst[1:]
return lst
print(delete_starting_evens([4, 8, 10, 11, 12, 15]))
print(delete_starting_evens([4, 8, 10]))
I get the following correct output:
[11, 12, 15]
[]
I don't understand why the order of the conditions around the and
statement matters. I thought that both conditions must be met to start the loop.