0

Please help me understand why when I feed a list that has more than one element to this function, it leaves one behind, but when I feed it with just one element, it successfully removes it.

def delete_starting_evens(my_list):
  for numbers in my_list:
    if my_list[0] % 2 == 0:
      my_list.remove(my_list[0])
  return my_list

print(delete_starting_evens([4, 8, 10]))
print(delete_starting_evens([8, 10]))
print(delete_starting_evens([10]))

Output:

[10]
[10]
[]

I expected the output of all 3 prints to be \[\]. I have also tried this with .pop and del() with identical results. I realize a cleaner way to write this would be to use a while loop and "remove" the first element with my_list\[1:\] instead, but I wanted to understand the logic and discrepancy behind my attempt with .remove

Amith A G
  • 378
  • 13
GYo
  • 1
  • 4
    Removing from a list while iterating it messes with the underlying iterator being iterated and causes elements to be skipped. It's generally advisable to not do this for that reason. The better option is to create a new list using a filtered list comprehension. – Carcigenicate Jul 02 '23 at 14:03
  • yes as @Carcigenicate said list comprehension option is best for this case(less code).I have added it in my answer section – Amith A G Jul 02 '23 at 14:40
  • Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – Pranav Hosangadi Jul 03 '23 at 17:49

2 Answers2

0

if the number is even the function removes that number from the list therefore the list size reduces and leads to the shifting of indices.
list comprehension method:

def delete_starting_evens(my_list):
   return [number for number in my_list if number % 2 != 0]
Amith A G
  • 378
  • 13
0

Inside the loop, you're checking if the first element is even. If it is, you remove the first element from the list. This caused the other elements to shift a position to left and the list size to reduce.

Thus the number that is being checked in the third iteration for #case 1 is at position 2 but the actual number has now been shifted to position 0. The condition is not checked and the list is returned with 10.

Try this to obtain the correct results:

for number in my_list[:]:  
   if number % 2 == 0:  
      my_list.remove(number)
AlefiyaAbbas
  • 235
  • 11