I want to know how to erase certain values on the list

Asked 2 years ago, Updated 2 years ago, 42 views

As far as I know, remove() only removes the first item that looks like it, so what should I do to erase all the items from the list?

The way I use it is not really Python, but it seems to be slow because there is an in-remove and duplicate search. Please let me know if there is a better way!

x = [1, 2, 3, 4, 2, 2, 3]
def remove_values_from_list(the_list, val):
    while val in the_list:
        the_list.remove(val)
remove_values_from_list(x, 2)

list python

2022-09-22 15:14

1 Answers

2.x :

x = [1,2,3,2,2,2,3,4]
filter(lambda a: a != 2, x)

3.x :

x = [1,2,3,2,2,2,3,4]
list(filter((2).__ne__, x))
def remove_values_from_list(the_list, val):
   return [value for value in the_list if value != val]

x = [1, 2, 3, 4, 2, 2, 3]
x = remove_values_from_list(x, 2)
def removeAllOccur(l, i):
    try:
        while True : l.remove(i)
    except ValueError:
        pass

x = [1, 2, 3, 4, 2, 2, 3]
removeAllOccur(x,10)


2022-09-22 15:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.