Search code examples
pythonlistduplicatesin-place

Why is my function not removing the last occurrence of elements from the list?


I am trying to implement a function that removes all the occurrences of a given number from a list using in-place. I tried this:

def removeElement(L, n):

  for i in L:
    if i == n:
      L.remove(i)
  return L

L = [1,1,2,3,3,3,4,3]
n = 3
v = removeElement(L,n)
print(v)

However it is not removing the last occurrence of '3' here giving [1,1,2,4,3] as output while expected output is [1,1,2,4]. Can someone point the mistake here.


Solution

  • You should use remove() to remove a certain number from an array, not a position.

    def remove_elements(num_list, item):
    
        items_count = num_list.count(item)
        for i in range(items_count):
            num_list.remove(item)
    
        return num_list
    
    num_list = [1,1,2,3,3,3,4,3]
    item = 3
    print(remove_elements(num_list, item))