Unique Elements from Both Lists in Python

Find elements that appear in exactly one of the two lists (symmetric difference).

IntermediateList ProgramsExample 24 of 25
unique-elements-from-both-lists.py
Run in browser
1# Program to find elements unique to each of two lists
2
3list1 = input("Enter first list elements: ").split()
4list2 = input("Enter second list elements: ").split()
5
6unique = list(set(list1) ^ set(list2))
7
8print("Elements unique to one list:", unique)

Output

Enter first list elements: 1 2 3
Enter second list elements: 3 4 5
Elements unique to one list: ['1', '2', '4', '5']

What's going on

We use the symmetric difference operator (^) on sets to get elements present in exactly one set.