Suppose I have a list L
of unknown objects, O1
to On
, and I want to remove another object reference M
which may refer to one of the objects in L
, I've managed to do it using:
L = [ O1, O2, ... On]
...
L = [ j for j in L if j not in [ M ] ]
which is lovely and idiomatic... but I'm having to do it a lot, and I wonder if there's not another more idiomatic way, or if there is not a faster way.
The important point is that the list of objects is unknown, and may or may not include the object to be excluded. I want to avoid extending or subclassing the objects where possible.
list.remove
seems to be the fastest way, with list comprehension as the second fastest and filter
at last.
Here are the timeit
results
In: python -m timeit '[x for x in [1,2,3,4,5] if x not in [4]]'
Out: 1000000 loops, best of 3: 0.285 usec per loop
In: python -m timeit '[x for x in [1,2,3,4,5] if x != 4]'
Out: 1000000 loops, best of 3: 0.254 usec per loop
In: python -m timeit 'filter(lambda x: x not in [4], [1,2,3,4,5])'
Out: 1000000 loops, best of 3: 0.577 usec per loop
In: python -m timeit 'filter(lambda x: x != 4, [1,2,3,4,5])'
Out: 1000000 loops, best of 3: 0.569 usec per loop
In: python -m timeit '[1,2,3,4,5].remove(4)'
Out: 10000000 loops, best of 3: 0.132 usec per loop
What about the built in filter function?
>>> l = [1,2,3,4,5]
>>> f = [4]
>>> filter(lambda x: x not in f, l)
[1, 2, 3, 5]
or in python3
>>> list(filter(lambda x: x not in f, l))
[1, 2, 3, 5]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With