Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest or most idiomatic way to remove object from list of objects in Python

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.

like image 810
Dycey Avatar asked Apr 29 '16 07:04

Dycey


2 Answers

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
like image 61
Muhammad Tahir Avatar answered Sep 30 '22 11:09

Muhammad Tahir


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]
like image 23
Francesco Avatar answered Sep 30 '22 11:09

Francesco