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)
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 want to use your code, you need to iterate over copy
of your original list. of your list
whats happening in your code, you are iterating over items in a list from which you are removing items. the for loop continues its iteration from the index on which it stays. but if you remove item from the list,you have moved your items for idx -1, because of that its "skiping" some items from your list
list = [2, 4, 6, 8, 10]
for i in list.copy():
divid = i %2
if divid == 0 :
list.remove(i)
print(list)
output:
[]
This is because you are removing the item from the same list you are iterating . Use lambda functions eg:
arr = [2, 4, 6, 8, 10]
print(list(filter(lambda x: x % 2, arr)))
instead.This would be the simplest method to achieve it