for loop to eliminate even numbers

Viewed 80

They want me to go through a list and delete all the instances of even numbers. I should keep deleting even numbers until I reach an uneven number.

When I call my function with the arugments 4,8 and 10, my function will return a 10. I don't know why, shouldn't my if statement solve that?

def delete_starting_evens(lst):
 for number in lst:
  if number%2==0 and len(lst)>0:
   lst.pop(0)
 else:
   break
return lst


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

The reason that your function does not work is because you are always doing:

lst.pop(0)

This line of code will always pop the first element, regardless of whether or not it is even or odd.

Instead of using a for each loop, you can use a for loop with a counter to account for the fact that the length of the list changes with each deletion:

def delete_starting_evens(lst):
  index = 0
  for counter in range(len(lst)):
   if lst[index] % 2 == 0:
    lst.pop(index)
    index -= 1
   else:
     break
   index += 1
  return lst


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

Let me explain the index increment and decrement now. After each iteration of the for loop, we want to check if the next element in the array is even, so we do:

index += 1

However, once we encounter an even element and pop it, the index of all the elements after it decrease by 1. This means that if we continue indexing, we will skip an element, so we need to account for this by decreasing our counter index every time we pop an element.

In a for-each-loop you don't have to test for the length of your list. You repeat it for every number in you list. So that your length will always be greater than 0.

Related