Please can someone help me with this?

Does anyone understand why this bit of code doesn’t work the way i want it to? Its this bit:

for num in lst:
if not num % 2 == 0:
lst.remove(num)

For some reason it won’t remove the odd numbers. However, if I change it to: (remove the “not”)

for num in lst:
if num % 2 == 0:
lst.remove(num)

It just removes all the even numbers. Ive tried != but it creates the same result.

Thanks in advance

1 Like

Consider whether it is possible to remove elements from a list while we iterate it. The trick would be to create a copy of the list, and iterate that, while removing from the original list.

list_copy = lst[:]  <<< shallow copy

for x in list_copy:
    if x % 2 != 0
    lst.remove(x)

 print (lst)
4 Likes

I guess you could iterate using the index instead, but that is messy.
You’d only increase the index if nothing was removed.

lst = [0, 1, 1, 2, 5, 8, 13, 21, 34] print(lst) i = 0 while(i < len(lst)): if not lst[i] % 2 == 0: lst.pop(i) # if index i has been removed, next index is i else: i += 1 print(lst)
1 Like