NEWBIE QUESTIION: Comparing Lists in Python

logistix logstx at bellatlantic.net
Wed May 1 22:32:27 EDT 2002


The most general way would be to just copy the list instead of using a dict
and remove the elements:

>>> diff = list1[:]
>>> for item in diff:
...  if item in list2:
...   diff.remove(item)
...
>>> diff
[1, 2, 3]

List comprehensions would be my favorite (although many will disagree):

>>> list1 = [1,2,3,4,5]
>>> list2 = [4,5,6,7,8]
>>> returnList1 = [val for val in list1 if val not in list2]
>>> returnList2 = [val for val in list2 if val not in list1]
>>> returnList1
[1, 2, 3]
>>> returnList2
[6, 7, 8]

Filter will also work:

>>> filter(lambda a,list2=list2:not a in list2, list1)
[1, 2, 3]


--
-

"Dianne van Dulken" <dianne at catsdogmac.com> wrote in message
news:5Z0A8.185$Q85.6597 at ozemail.com.au...
> Hi everyone,
>
> I haven't been using python for very long, so I hope you will forgive me
if
> I am asking a stupid question, or doing this in a stupid way.
>
> I am trying to compare two lists in Python, which have been passed into
it.
> I want to return the difference between the two lists as again two lists
>
> eg:
>
> list 1 = item1, item5, item8, item10
> list2 = item 3, item4, item5
>
> I want to return
>
> returnlist1 = item1, item8, item10
> returnlist2 = item3, item4
>
> I haven't been working in python very long, but from what I have read, the
> best way is to convert these to a dictionary, and compare there.  This is
> what I have done so far.
>
> list1 = list1.split(',')
> list2 = list2.split(',')
>
> returnlist1 = []
> returnlist2 = []
>
> d = {}
> for item in list1:
>   if item not in list2:
>    d[item] = item
> if d:
>  returnlist1 = d.values()
>
> d2 = {}
> for item in list2:
>  if item not in list1:
>     return item
>     d2[item] = item
> if d2:
>  returnlist2 = d2.values()
>
> return [returnlist1,returnlist2]
>
>
> I found if I didn't include the split, but just passed in a list like
> "list1=[item1, item3, item] it would work only on 1 character at a time
and
> not recognise it was a split.
>
> Please let me know if I am doing this in a very stupid way.  The problem
is
> that it isn't always recognising the lists, or comparing correctly.  It
> finds returnlist1 OK, but not returnlist2.
>
> I'm using python scripts in Zope if that may also be causing a problem.
>
> Thanks very much
>
> Di
>
>
> --
> Dianne van Dulken
> (put out the cats to talk to me)
>
> See the cutest puppy in the known universe (as voted by Rick and i)
> http://www.dogmac.com/bartholomew
>
>





More information about the Python-list mailing list