Codecademy Forums

Code challenge lists - improving my solution [solved]

Heyo, I was wondering if you could help me understand this:

My initial attempt was to try and .pop the first (0th?) element from the list, using the following code:

def delete_starting_evens(lst):
i = 0
while lst[i] % 2 == 0:
lst.pop(i)
return lst

Which works for list#1. I quickly realized I had been a bit too eager, though, having proceeded without fully reading the exercise - it needs to work even if every element is even. So I came up with:

def delete_starting_evens(lst):
  if len(lst) > 0:
    i = 0
    while lst[i] % 2 == 0:
      lst.pop(i)
    return lst
  else:
    return lst

but this throws a tab error. To my naive mind it seems as if the lines are correctly indented? I had to edit my code a couple times when pasting it here as it came out with different indentations than in my script (a clue!), which I promptly changed and ran again to no avail.
What am I missing here?

Will this line raise an error when the list is empty?

Do we even need a variable, i?

while lst[0] % 2 == 0
    lst.pop(0)

Hm, so I was hoping “if len(lst) > 0:” would handle the empty list;
as for the i variable, I was thinking it would be necessary for the .pop(i) but I take it from your reply .pop(0) will do the same job

1 Like

It will catch it on the inputs, but not in the loop.

Aah gotcha, so after the popping commences it won’t kick in. I’ll try and adapt it. Thanks for the help!

1 Like
def delete_starting_evens(lst):
  if len(lst) > 0:
    while lst[0] % 2 == 0:
      lst.pop(0)
      if len(lst) == 1:
        return lst
    return lst
  else:
    return lst

totally worked! Thank you! Not so pretty perhaps but hey, satisfying af

What if that line returns a list with an even number in it?

…back to the drawing board

1 Like