Standard ways to get union, intersection, difference of lists?

Erik Max Francis max at alcyone.com
Thu Jun 26 05:28:59 EDT 2003


Mickel Grönroos wrote:

> Are there any standard list methods for getting the intersection and
> difference of two lists? (The union is easy ("list1.extend(list2)"),
> unless you want it to contain unique values.)

If you have Python 2.3 available, why not use a set?

>>> import sets
>>> s1 = sets.Set([1, 2, 3])
>>> s2 = sets.Set([3, 4])
>>> s1.intersection(s2)
Set([3])
>>> s1.difference(s2)
Set([1, 2])
>>> s2.difference(s1)
Set([4])

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ Only the ephemeral is of lasting value.
\__/  Ionesco




More information about the Python-list mailing list