list_a-list_b

David Eppstein eppstein at ics.uci.edu
Wed Apr 17 01:29:07 EDT 2002


In article <mailman.1019017052.23597.python-list at python.org>,
 Michael Gilfix <mgilfix at eecs.tufts.edu> wrote:

>   Here's a one line example that doesn't touch either of the lists
> that you might like and I think it pretty clear.
> 
>   new list = filter (lambda x, list=list b: x not in b, list a)

It's not completely clear to me (I think some of your spaces should be 
underscores, and how come the lambda function ignores its second 
argument).  I also don't see why this should be better than

    new_list = [x for x in list_a if x not in list_b]

In any case both of these will take time proportional to the product of 
the two lists' lengths, not good.

Better is to convert b to a dictionary
(where are dict comprehensions when you need them):

    dict_b = {}
    for x in list_b: dict_b[x] = 1
    new_list = [x for x in list_a if x not in dict_b]

-- 
David Eppstein       UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/



More information about the Python-list mailing list