0

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.

Edd
  • 1
  • 1
  • The right hand side expression is only evaluated if the left hand side is truthy. – deceze Jan 19 '23 at 11:30
  • In the condition `len(lst)>0 and lst[0]%2==0`, if `len(lst)>0` is false then `lst[0]%2==0` will not be evaluated, which in that case prevents an index error, since `lst[0]` would not exist. – khelwood Jan 19 '23 at 11:31
  • 1
    Why not find the first index to keep (if any) and then do a single slice? No need to slice away one item at a time. – John Coleman Jan 19 '23 at 12:19

0 Answers0