Sorting by item_in_another_list

Steven Bethard steven.bethard at gmail.com
Thu Oct 26 16:43:40 EDT 2006


Paul Rubin wrote:
> Steven Bethard <steven.bethard at gmail.com> writes:
>> Cameron Walsh wrote:
>>> Which brings me to the question, would this solution:
>>> B = set(B)
>>> A = B + list(x for x in A if x not in B)
>>> be faster than this solution:
>>> B = set(B)
>>> A.sort(key=B.__contains__, reverse=True)
>> [timings deleted]
>> That said, I'd probably still use the first solution -- it's more
>> immediately obvious why that one works.
> 
> Wait a minute, the first example looks wrong, B has gotten replaced by
> a set and then it's added to a list.

Yep.  If you look back at the lines I actually timed, they were::

     B_set = set(B)
     A = B + list(x for x in A if x not in B_set)

and::

     B_set = set(B)
     A.sort(key=B_set.__contains__, reverse=True)

As you noted, you'll get an error if you try to concatenate B as a set 
to the list.

Steve



More information about the Python-list mailing list