ordered sets operations on lists..

Bengt Richter bokr at oz.net
Sun Feb 12 14:44:01 EST 2006


On Sat, 11 Feb 2006 10:24:04 -0800, aleaxit at yahoo.com (Alex Martelli) wrote:

>Raymond Hettinger <python at rcn.com> wrote:
>   ...
>> The intersection step is unnecessary, so the answer can be simplified a
>> bit:
>> 
>> >>> filter(set(l2).__contains__, l1)
>> [5, 3]
>> >>> filter(set(l1).__contains__, l2)
>> [3, 5]
>
>...and if one has time to waste, "setification" being only an
>optimization, it can also be removed: filter(l2.__contains__, l1) etc
>(very slow for long lists, of course).
>
>Personally, I'd always use (depending on guesses regarding lengths of
>lists) [x for x in l1 if x in l2] or the setified equivalent, of course.
>
Perhaps newbies should be advised that

    [x for x in l1 if x in set(l2)]

is not a (well) setified equivalent? I could see them being tempted.

Regards,
Bengt Richter



More information about the Python-list mailing list