filter list fast

Fredrik Lundh fredrik at pythonware.com
Sat Mar 18 05:35:55 EST 2006


lars_woetmann wrote:

> I have a list I filter using another list and I would like this to be
> as fast as possible right now I do like this:
>
> [x for x in list1 if x not in list2]
>
> i tried using the method filter:
>
> filter(lambda x: x not in list2, list1)
>
> but it didn't make much difference, because of lambda I guess
> is there any way I can speed this up

if list2 is a list object, "not in list2" is an O(N) operation.

maybe you should use sets instead ?  does the following work
better ?

    set2 = set(list2)
    result = [x for x in list1 if x not in set2]

?

</F>






More information about the Python-list mailing list