Sep 17, 2019

Python remove all occurrences a given element from the list

#Method1
#Use the same list (don't use another list)
lista = [10, 10, 20, 10, 30, 10, 40, 10, 50]
print(lista)
#o/p: [20, 30, 40, 50]

#Note:
#Every time when you remove item, list index changes

n = 10 #element to remove

print('------Method1-----')
i = 0
listlen = len(lista)
while(i < listlen):
  if lista[i] == n:
    lista.remove(n)
    listlen -= 1
    continue
  i += 1

print(lista)   #[20, 30, 40, 50]


#Method2
print('-----Method2-----')
#Remove element and copy to another list
lista = [10, 10, 20, 10, 30, 10, 40, 10, 50]
listb = list(filter(lambda x: x != 10, lista))
print(listb)   #[20, 30, 40, 50]
listb = [i for i in lista if i != 10]
print(listb)   #[20, 30, 40, 50]

No comments:

Post a Comment