A "for" with "list" question.

Frank Buss fb at frank-buss.de
Sun Sep 1 19:09:46 CEST 2002


Sean 'Shaleh' Perry <shalehperry at attbi.com> wrote:

> oddballs = []
> for item in b:     # iterate over one list
>     if item in a:   # test if it is in the other list
>         print item
>     else:
>         oddballs.append(item)
> 
> for item in oddballs:
>     print item

That's wrong, because you won't get 0, which is in a, but not in b. 
Derived from the nice solution from Graham I would write:

>>> a = [0,1,2]
>>> b = [1,2,3]
>>> inBothLists = [item for item in a if item in b]
>>> inOneListOnly = [item for item in a+b if item not in inBothLists]
>>> print inBothLists
[1, 2]
>>> print inOneListOnly
[0, 3]

-- 
Frank Buß, fb at frank-buss.de
http://www.frank-buss.de, http://www.it4-systems.de



More information about the Python-list mailing list