Let\'s say I have two lists, l1
and l2
. I want to perform l1 - l2
, which returns all elements of l1
not in l2
Expanding on Donut's answer and the other answers here, you can get even better results by using a generator comprehension instead of a list comprehension, and by using a set
data structure (since the in
operator is O(n) on a list but O(1) on a set).
So here's a function that would work for you:
def filter_list(full_list, excludes):
s = set(excludes)
return (x for x in full_list if x not in s)
The result will be an iterable that will lazily fetch the filtered list. If you need a real list object (e.g. if you need to do a len()
on the result), then you can easily build a list like so:
filtered_list = list(filter_list(full_list, excludes))