0

I have two lists:

listOne = ['John', 'James', Daniel', 'Peter', 'Luke']
listTwo = ['Daniel', 'Peter', Kate', 'Jenny']

I want to compare these two lists and return the non matches, and if need be, save this to another list, so the output should be:

Non-Matches: 'Kate', 'Jenny'

How can I achieve this? I looked at changing the lists to sets but have had no luck getting it working

luchad95
  • 75
  • 1
  • 10
  • 1
    Does this answer your question? [Python, compute list difference](https://stackoverflow.com/questions/6486450/python-compute-list-difference) – J'e Sep 30 '20 at 11:38
  • why 'James', 'John', 'Luke' are not in output ? they are also non match ? – Omer Anisfeld Sep 30 '20 at 11:45
  • I am having an issue as I am reading in the first list from a text file, the list is showing up as listOne = ["'John', 'James', Daniel', 'Peter', 'Luke'"] , it has speech marks at the start and end, will this effect comparison? it does not work – luchad95 Sep 30 '20 at 12:07

2 Answers2

4

you can use set , look at this function :

def list_diff(list1, list2):
    return (list(list(set(list1)-set(list2)) + list(set(list2)-set(list1))))
diff_values = list_diff(listOne, listTwo) # call to this function 

python set : https://docs.python.org/2/library/sets.html

Omer Anisfeld
  • 1,236
  • 12
  • 28
  • I am having an issue as I am reading in the first list from a text file, the list is showing up as listOne = ["'John', 'James', Daniel', 'Peter', 'Luke'"] , it has speech marks at the start and end, will this effect comparison? it does not work – luchad95 Sep 30 '20 at 12:00
  • yes you have now list is len =1 of 1 item, try listOne = [l.replace("'",'') for l in listOne[0].split(',')] to make it a list of several items splited by comma – Omer Anisfeld Oct 01 '20 at 10:16
0

You can use set to do that

listOne = set(['John', 'James', 'Daniel', 'Peter', 'Luke'])
listTwo = set(['Daniel', 'Peter', 'Kate', 'Jenny'])
print(list(listTwo - listOne))

Output

['Kate', 'Jenny']
Ajay Verma
  • 610
  • 2
  • 12
  • I am having an issue as I am reading in the first list from a text file, the list is showing up as listOne = ["'John', 'James', Daniel', 'Peter', 'Luke'"] , it has speech marks at the start and end, will this effect comparison? it does not work – luchad95 Sep 30 '20 at 12:00