"list index out of range" in Delete Starting Evens?

I’d appreciate if someone can look at this code. At the bottom you’ll see two different inputs run and printed; the first works, the second doesn’t.

Here’s the code:

def delete_starting_evens(lst):
  at_least_one_odd = True
  for i in lst:
    check_for_odd = i % 2
    if check_for_odd != 0:
      at_least_one_odd = True  
  while at_least_one_odd:
    if lst[0] % 2 == 0:
      lst.pop(0)
    else:
      at_least_one_odd = False
  return lst

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

Here’s the output:

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

Help?

Hello! That is because once the while loop removes all of the even numbers in the list [4, 8, 10], it still iterates through the list. Since all of the items are removed by that time, it is an empty list ([]). Empty lists don’t have anything in them, so even the list index 0 is out of range for an empty list.
I hope this helps!

Got it! That makes sense.

I’m guessing a break would fix this. Can you advise where to put it?

You wouldn’t need to have a break. You could simply check to see if if the length of the list is greater than 0 (an empty list):

if len(lst) > 0 and lst[0] % 2 == 0:
 #code

Actually, now that I look back, the real problem was that I forgot what I was doing an abandoned my strategy half-way through. I got this code working:

def delete_starting_evens(lst):
  empty_list = []
  at_least_one_odd = True
  for i in lst:
    check_for_odd = i % 2
    if check_for_odd != 0:
      at_least_one_odd = True
    else:
      at_least_one_odd = False
  while at_least_one_odd:
    if lst[0] % 2 == 0:
      lst.pop(0)
    else:
      at_least_one_odd = False
    if at_least_one_odd == False:
      return empty_list
    else:
      return lst

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

You might have noticed that my for statement didn’t seem to be doing anything because I never specified a condition that would switch it to False or tell Python what to do if it was false. I did a jury rig to return an empty list if there were no odds… sort of like turning in my calculus homework with the answer but no calculation because I knew what the answer should be.

1 Like

That’s great that you’ve got your code to work! Now, is there any way you can refractor that? Consider what the for and while loops are doing? Is there a way you could combine them?

1 Like

Probably. I’ve learned that if it takes more than one or two edits I’ve completely missed the way I was “supposed” to do something.