Best way to remove elements from a list

list, python

Solution

Use a list comprehension:

Scenario 1:

[item for item in my_list if 1 <= item <=5 ]

Scenario 2:

to_be_removed = {'a', '1', 2}
[item for item in my_list if item not in to_be_removed ]

Scenario 3:

[item for item in my_list if some_condition()]

Scenario 4(Nested list comprehension):

[[item for item in seq if some_condition] for seq in my_list]

Note that if you want to remove just one item then `list.remove`, `list.pop` and `del` are definitely going to be very fast, but using these methods while iterating over the the list can result in unexpected output.

Related: Loop “Forgets” to Remove Some Items

Problem

I would like to know what is the best way/efficient way to remove element(s) from the list. There are few functions provided by Python: - `some_list.remove(value)`, but it throws error if value is not found. - `some_list.pop(some_list[index])`, removes the item at the given position in the list, and return it. - `del (some_list[index])`, it removes element from the given index, it's different from pop as it doesn't return value. Scenarios: - If you have few items to remove say one element or between 1 to 5. - If you have to remove multiple items in a sequence. - If you have to remove different items based on a condition. - How about if you have a list of lists and want to remove elements in sequence.

Original source

Related problems