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

Time:10-26

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.

CodePudding user response:

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))

CodePudding user response:

new_list= []
def removeElement(L, n):

  for i in range(len(L)) :
  
    if L[i] != n:
      new_list.append(L[i])


  return new_list

 

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