Search code examples
pythoncompare

Python - Use 'set' to find the different items in list


I need to compare two lists in Python, and I know about using the set command to find similar items, but is there a another command I could use that would automatically compare them, instead of having to code for it?

I would like to find the items that aren't in each one. Say list one is as follows:

[1, 2, 3, 4, 5, 6] 

and list two is:

[1, 2, 3, 4, 6]

I want to find that 5 is missing from the list, hopefully by a command, but I do know how to loop through comparing.


Solution

  • Looks like you need symmetric difference:

    a = [1,2,3]
    b = [3,4,5]
    
    print(set(a)^set(b))
    
    
    >>> [1,2,4,5]