Determine differences in lists in Python

Sometimes, you just want to take two lists like a previous one and a new one and get back information about what is new, what is old, and what is the same.  Here is one way to do it.

def compareLists(old, new):
  oldset = set(old)
  addlist = [x for x in new if x not in oldset]
  newset = set(new)
  dellist = [x for x in old if x not in newset]
  samelist = [x for x in old if x in newset]
  return (addlist, dellist, samelist)
old = ['One', 'Two', 'Three', 'Four']
new = ['One', 'Two', 'Five']

(addlist, dellist, samelist) = compareLists(old, new)
print("addlist=", addlist)
print("dellist=", dellist)
print("samelist=", samelist)

what you get is:

('addlist=', ['Five'])
('dellist=', ['Three', 'Four'])
('samelist=', ['One', 'Two'])

With this, you can take “instantiation” action with the “add” list, take “removal” action with the “del” list, and simply update data with the “same” list.