[Tutor] comparing lists of strings with each other

Karl Pflästerer sigurd at 12move.de
Wed Feb 4 13:04:33 EST 2004


jan willem maaskant <- janwillem.maaskant at planet.nl wrote:

> i have a problem, with comparison of two strings in a list using the filter
> function.
> and i really don't know the solution.
[...]
> for example:

> listOne  = [ 'a','b','c']
> listTwo  = ['a','c']

> i want to remove the strings in listOne which are equal to the strings in
> listTwo.
> 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

Do not use list as parameter; it's a builtin.

Did you read what the filter function does?  It iterates over a sequence
and returns those elemenst for which the functions returns a true
value.  Above function will always return True for the values  you gave;
e.g:
    a != c => True
    b != a => True
    c != a => True

>>>> listThree = filter(removeStrings, listOne)
> however this results in
>>>> listThree
> ['a', 'b', 'c']

So the result is exactly that what you asked for.

> seems to work quite fine
> if I put this code in

>>>> def removeStrings(list):
>     for key in listTwo:
>         if key == list:    # i changed the comparison operator
>             return list

> than the function gives exactly what i expected:

>>>> listThree = filter(removeStrings, listOne)
>>>> listThree
> ['a', 'c']

Above you wrote you wanted the difference between the two lists.  Now
you write the intersection is what you want?  Which one is true?

Anyway I assume you meant what you first wrote.

First a solution nearly the same as yours.  What you need is a function
which returns *False* if a value from one list is not in the other list.

Python has something like that builtin; `in'

>>> L = [1,2,3]
>>> 1 in L
True
>>> 4 in L
False
>>> 

So you simply have to call `in' for the elements of list1 with list2 and
negate the result.

>>> listOne  = [ 'a','b','c']
>>> listTwo  = ['a','c']
>>> filter(lambda el: not el in listTwo, listOne)
['b']
>>> 

If you wanted the intersection just don't negate the result.

If you have longer lists it might be better to use the new set module
(it works with dictionaries) otherwise the code might be to slow.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list




More information about the Tutor mailing list