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]
CodePudding user response:
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]
CodePudding user response:
Try this:
def remove_multiples(lst, num):
return list(filter(lambda x: x % num, lst))
l = [3, 5, 2, 6, 8, 9]
print(remove_multiples(l, 2)) # [3, 5, 9]
CodePudding user response:
The reason is that the size of the list changes during iteration. After removing 2 from the list (index 2), you access index 3, which is no longer 6, but 8
In such cases it is better to iterate over a copy of the object. In this way, changes during iterations can be avoided.
This should work
def remove_multiples(l, n):
for element in l[:]:
if element % n == 0:
l.remove(element)
return l
l = [3, 5, 2, 6, 8, 9]
print(remove_multiples(l, 2))
CodePudding user response:
Each time you remove an element from your list, the length of the list shortens. Thus, you are not cycling through all the elements in your list. In other words, your while loop never gets to 6. This is why it is not removed.
Try this:
def remove_multiples(l, n):
return [element for element in l if (element % n)]
l = [3, 5, 2, 6, 8, 9]
print(remove_multiples(l, 2))