NEWBIE QUESTIION: Comparing Lists in Python

Dianne van Dulken dianne at catsdogmac.com
Wed May 1 21:52:01 EDT 2002


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