[Tutor] comparing lists of strings with each other

Rich Krauter rmkrauter at yahoo.com
Wed Feb 4 12:38:46 EST 2004


If you trace out each step of what filter is doing,
you'll see why you are getting what you are getting.

By using filter, you are passing each element of the
first list into your comparison function. Your
comparison  function compares the passed-in item with
each item in the second list, and returns the item (a
true value) when the two are not equal:

'a' in list1 != 'c' in list2, so 'a' is returned
'b' in list1 != 'a' in list2, so 'b' is returned
'c' in list1 != 'a' in list2, so 'c' is returned

Filter is documented here:
http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-26

You can do this without filter, using list membership
tests:
>>> newlist = []
>>> for x in list1:
... 	if x not in list2:
... 		newlist.append(x)

or

>>> f = lambda i: i not in list2
>>> filter(f,list1)
>>> ['b']

One way you can do what you want in python 2.3 is with
sets:  
>>> import sets
>>> a1 = ['a','b','c']
>>> a2 = ['a','c']
>>> s1 = sets.Set(a1)
>>> s2 = sets.Set(a2)

#find all elements of s1 not in s2 
>>> list(s1-s2)
['b']

Rich

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/



More information about the Tutor mailing list