I'm trying to remove even numbers from a list. My final output is [4,8] but it is supposed to be empty.
list = [2, 4, 6, 8, 10]
for i in list:
divid = i %2
if divid == 0 :
list.remove(i)
print(list)
You are modifying the list as you iterate over it. Imagine a pointer moving along the list. For the first iteration, the index is 0 (and i is 2). You remove the first value and return to the start of the loop.
The index is incremented (to 1) and i is now the second value in the list (now 6) which is also removed. Notice that 4 is now 'behind' the index of the iterator and will never be reached. Continuing along the list you will remove every second value leaving [4, 8].
A couple of pointers. To loop over a list like this you can use for i in list[:]: which copies the list before iterating over it. Also avoid naming variables things like list which override builtin types. You'll cause bugs later in your code.
As others have pointed out, you should not modify a list and iterate over it at the same time. The simplest solution is to create a new list with the required modifications:
lst = [2, 4, 6, 8, 10]
new_lst = [i for i in lst if i % 2 != 0]
The above uses a list comprehension to create a new list with only the odd elements - which is the same as removing the even elements from the original list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With