So I wanted to delete the multiples of a number (in this case 2) inside a list. My code basically works put for some reason the number 6 doesn’t get removed any idea how I can fix this?
Input:
def remove_multiples(l, n):
i = 0
while i < len(l):
element = l[i]
if element % n == 0:
l.remove(element)
i += 1
return l
l = [3,5,2,6,8,9]
print(remove_multiples(l, 2))
Output:
[3, 5, 6, 9]
>Solution :
I added a print statement to the remove_multiples function to see how the loop is behaving. I think it might be useful to understand what is happening following your approach
def remove_multiples(lst, num):
i = 0
while i < len(lst):
# let's add a print to check how the loop is behaving
print(f"indexing elem {i}: value{l[i]}")
if l[i] % num == 0:
# we remove the item. even if we do not update i, due to the removal of the lst item, when the next iteration starts i will access the next element
l.pop(i)
else:
# we continue
i += 1
return lst
# or using list comphrension
def remove_multiples_v2(lst, num):
[i for i in lst if i % num != 0]