Functional approach:
Python 3.x
>>> x = [1,2,3,2,2,2,3,4]
>>> list(filter((2).__ne__, x))
[1, 3, 3, 4]
or
>>> x = [1,2,3,2,2,2,3,4]
>>> list(filter(lambda a: a != 2, x))
[1, 3, 3, 4]
or
>>> [i for i in x if i != 2]
Python 2.x
>>> x = [1,2,3,2,2,2,3,4]
>>> filter(lambda a: a != 2, x)
[1, 3, 3, 4]
Answer from Mark Rushakoff on Stack OverflowFunctional approach:
Python 3.x
>>> x = [1,2,3,2,2,2,3,4]
>>> list(filter((2).__ne__, x))
[1, 3, 3, 4]
or
>>> x = [1,2,3,2,2,2,3,4]
>>> list(filter(lambda a: a != 2, x))
[1, 3, 3, 4]
or
>>> [i for i in x if i != 2]
Python 2.x
>>> x = [1,2,3,2,2,2,3,4]
>>> filter(lambda a: a != 2, x)
[1, 3, 3, 4]
You can use a list comprehension:
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)
print x
# [1, 3, 4, 3]
Remove all instances of a value from a list
How to remove all occurrences of an element from list in Python? - Stack Overflow
Remove the second occurrence of a value from a list if it appears more than once
how to remove all instances of an element in a list?
There is no remove_all method or anything like that, but the best ways to accomplish this are with a list comprehension or filter.
Assuming that ls only contains other lists you can write the following to remove all occurrences of the empty list []:
List Comprehension
ls = [[1], [1, 2], [1, 2, 3], [], [2], [2, 3], [], [], [3]]
ls = [x for x in ls if x]
# now ls = [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
Filter
ls = [[1], [1, 2], [1, 2, 3], [], [2], [2, 3], [], [], [3]]
ls = list(filter(None, ls))
# now ls = [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
Generalizing for more than just the empty list
If you wanted to remove all occurrences of a given element elem (that is not the empty list) you can modify the above code as follows:
ls = [x for x in ls if x != elem]
##### or #####
ls = list(filter(lambda x: x != elem, ls))
A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built-in dict, list, and tuple classes, and the collections module.)
https://docs.python.org/3.8/library/stdtypes.html#set-types-set-frozenset