ordered sets operations on lists..

Scott David Daniels scott.daniels at acm.org
Fri Feb 10 14:18:23 EST 2006


Amit Khemka wrote:
> Hello, Is there a *direct* way of doing set operations on lists which
> preserve the order of the input lists ?
Nope

> For Ex.  l1 = [1, 5, 3, 2, 4, 7]
>             l2 =  [3, 5,  10]
> 
> and (l1 intersect l2)  returns [5, 3]     .... (and (l2 intersect l1) 
> returns [3, 5])

However:
     intersection = set(list1) & set(list2)
     [element for element in list1 if element in intersection]
or
     [element for element in list2 if element in intersection]
Give you the result you'd like.

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list