Sorting by item_in_another_list

J. Clifford Dyer jcd at
Wed Oct 25 18:16:30 CEST 2006

ZeD wrote:
> Paul Rubin wrote:
>>> A = [0,1,2,3,4,5,6,7,8,9,10]
>>> B = [2,3,7,8]
>>> desired_result = [2,3,7,8,0,1,4,5,6,9,10]
>> How about:
>>   desired_result = B + sorted(x for x in A if x not in B)
> this. is. cool.

Cool, yes, but I'm not entirely sure it does what the OP wanted.  Partly 
because I'm not entirely sure what the OP wanted.  Counter example:

Given these variables:

A = [0,1,2,3,4,5,6,8,9,10]  # Note 7 is missing
B = [2,3,7,8]

which of the following should the function yield?

desired_result = [2,3,7,8,0,1,4,5,6,9,10]
desired_result2 = [2,3,8,0,1,4,5,6,9,10]

The fact that we are ostensibly sorting A makes me thing it should be 
the latter, but the example given was ambiguous.  If we are in fact 
looking for desired_result2, maybe we should use:

result = [ x for x in B if x in A ] + [ x for x in A if X not in B ]

or like the sibling post suggests: substitute set(A) and set(B) for the 
"in" argument in each comprehension.


More information about the Python-list mailing list