filter list fast

Klaus Alexander Seistrup klaus at seistrup.dk
Sat Mar 18 05:41:01 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 you use a reasonably new python version, you could use sets:

#v+

>>> a = set(range(10))
>>> a
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = set(range(5, 15))
>>> b
set([5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
>>> a.difference(b)
set([0, 1, 2, 3, 4])
>>> a-b
set([0, 1, 2, 3, 4])
>>> list(a-b)
[0, 1, 2, 3, 4]
>>> 

#v-

Cheers, 

-- 
Klaus Alexander Seistrup
SubZeroNet, Copenhagen, Denmark
http://magnetic-ink.dk/



More information about the Python-list mailing list