[Tutor] comparing lists of strings with each other
anna at aleax.it
Wed Feb 4 15:39:32 EST 2004
On Wednesday 04 February 2004 04:47 pm, jan willem maaskant wrote:
> i have two lists filled with strings and i want to filter the strings from
> one list out of the other.
You'd be better off with a list comprehension.
threelist = [i for i in onelist if i not in twolist]
But, if you really must use filter for some reason....:
> for example:
> listOne = [ 'a','b','c']
> listTwo = ['a','c']
> i want to remove the strings in listOne which are equal to the strings in
> So the list i want to have must look like this.
> listThree = ['b']
> i tried it with the following code:
> >>> def removeStrings(list):
> for key in listTwo:
> if key != list:
> return list
> >>> listThree = filter(removeStrings, listOne)
First, you really really don't want to use "list" as an argument or variable
name. list is one of the built-in types in Python, and you *REALLY* don't
want to use it as a variable name.
> however this results in
> >>> listThree
> ['a', 'b', 'c']
> so this is wrong, but what i really don't understand, is why the opposite
> seems to work quite fine
> if I put this code in
Okay, in order to see what's happening, I added some print statements to the
function. then ran the whole thing again.
alist = ['d', 'b', 'c']
blist = ['d', 'f', 'b']
print 'filter passes item', item
for key in blist:
print "key is ", key
if key != item:
print "key != item. returning", item
clist = filter(remstring, alist)
filter passes item d
key is d
key is f
key != item. returning d
filter passes item b
key is d
key != item. returning b
filter passes item c
key is d
key != item. returning c
['d', 'b', 'c']
Does this help you see what's happening?
There is a type 3 error in which your mind goes totally blank whenever you try
to remember which is which of type 1 and type 2.
More information about the Tutor