comparing two lists

J

jimgardener

hi
I have two lists of names.I need to find the difference between these
two lists.I tried to do it using sets.But I am wondering if there is a
better way to do it.Please tell me if there is a more elegant way.
thanks,
jim

my code snippet follows..

oldlst=['jon','arya','ned','bran']
newlst=['jaime','jon','cersei']

newlyadded=set(newlst)-set(oldlst)
removed=set(oldlst)-set(newlst)
unchanged=set(oldlst)& set(newlst)
print '%d were newly added= %s'%(len(newlyadded),list(newlyadded))
print '%d were removed=%s'%(len(removed),list(removed))
print '%d were unchanged=%s'%(len(unchanged),list(unchanged))

this produces the output
 
V

Vlastimil Brom

2010/3/5 jimgardener said:
hi
I have two lists of names.I need to find the difference between these
two lists.I tried to do it using sets.But I am wondering if there is a
better way to do it.Please tell me if there is a more elegant way.
thanks,
jim

my code snippet follows..

oldlst=['jon','arya','ned','bran']
newlst=['jaime','jon','cersei']

newlyadded=set(newlst)-set(oldlst)
removed=set(oldlst)-set(newlst)
unchanged=set(oldlst)& set(newlst)
print '%d were newly added= %s'%(len(newlyadded),list(newlyadded))
print '%d were removed=%s'%(len(removed),list(removed))
print '%d were unchanged=%s'%(len(unchanged),list(unchanged))

this produces the output

Hi,
I guess for lists with unique items and order insignificant this is
just fine; you may also check difflib, if it suits your needs; there
are multiple comparing and displaying possibilities, e.g.:
import difflib
print "\n".join(difflib.unified_diff(['jon','arya','ned','bran'], ['jaime','jon','cersei']))
---

+++

@@ -1,4 +1,3 @@

+jaime
jon
-arya
-ned
-bran
+cersei
hth,
vbr
 
T

Terry Reedy

hi
I have two lists of names.I need to find the difference between these
two lists.I tried to do it using sets.But I am wondering if there is a
better way to do it.Please tell me if there is a more elegant way.
thanks,
jim

my code snippet follows..

oldlst=['jon','arya','ned','bran']
newlst=['jaime','jon','cersei']

newlyadded=set(newlst)-set(oldlst)
removed=set(oldlst)-set(newlst)
unchanged=set(oldlst)& set(newlst)

Except for the duplicate calls to set, this is fine. If order and
duplication are irrelevant (and hashability is guaranteed), use sets to
start with.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,740
Latest member
JudsonFrie

Latest Threads

Top