How to remove all occurrences of an element from list in Python?

Saykat :
ls = [[1], [1, 2], [1, 2, 3], [], [2], [2, 3], [], [], [3]]

Is there any python list method that will enable me to remove all the similar items at once. For example, I have a 2d list 'ls' which has three empty list items []. I want to remove all the empty list items at once. I know it can be done with 'remove' and 'loop.' But is there any method to do the operation at once? To be simple: I want all the '[]' to be deleted. And thus the answer would be like this. [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]

illiteratecoder :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=298097&siteId=1