Efficient List Subtraction

Steven D. Majewski sdm7g at Virginia.EDU
Fri Apr 23 21:35:32 EDT 1999


On Fri, 23 Apr 1999, KELLEY SCOTT T wrote:

> 
> Does anyone out there have a simple way to compare two lists (some operator perhaps) and
> return
> a list of *differences*?  By differences, I mean the following:  If had two
> lists  like,
> 
> a = [1, 4, 5, 100]
> b = [4, 5]
> 
> the difference between a and b (a-b) would be [1, 100]. I suppose you could
> write a couple of for loops to go through each list and compare them, but I
> thought there might be a simple way to do this.
> 
> I'm also interested in a simple way to returning a list of what is identical between the
> two lists.
> In the case of the above lists, a and b, they both contain [4, 5].
> 

Well -- it's probably not the most efficient, but the simplest 
list intersection  is probably:

>>> a = [1,4,5,100]
>>> b = [4,5]
>>> filter( lambda x: x in a, b )
[4, 5]
>>> filter( lambda x: x in b, a )		# order doesn't matter
[4, 5]						# for intersection

					# but it does for set-difference
>>> filter( lambda x: x not in a, b )		# b - a 
[]
>>> filter( lambda x: x not in b, a )		# a - b 
[1, 100]


I don't think union or XOR can be done as concisely. 


---|  Steven D. Majewski   (804-982-0831)  <sdm7g at Virginia.EDU>  |---
---|  Department of Molecular Physiology and Biological Physics  |---
---|  University of Virginia             Health Sciences Center  |---
---|  P.O. Box 10011            Charlottesville, VA  22906-0011  |---

    Caldera Open Linux: "Powerful and easy to use!" -- Microsoft(*)
     (*) <http://www.pathfinder.com/fortune/1999/03/01/mic.html>
 





More information about the Python-list mailing list