faqts : Computers : Programming : Languages : Python : Snippets : Lists

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

22 of 22 people (100%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

Efficient list subtraction

Jul 5th, 2000 09:59
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 95, Steven D. Majewski


"""
Packages: basic_datatypes.lists;functional_programming
"""
""" 
> 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]
print filter( lambda x: x in a, b )
# [4, 5]
print filter( lambda x: x in b, a )     # order doesn't matter
# [4, 5]                                # for intersection
                                        # but it does for set-difference
print filter( lambda x: x not in a, b )       # b - a 
# []
print filter( lambda x: x not in b, a )       # a - b 
# [1, 100]
"""
I don't think union or XOR can be done as concisely. 
"""