List Difference in Python

Find elements that are in the first list but not in the second.

BeginnerList ProgramsExample 25 of 25
list-difference.py
Run in browser
1# Program to find list difference (A - B)
2
3list1 = input("Enter first list elements: ").split()
4list2 = input("Enter second list elements: ").split()
5
6difference = [x for x in list1 if x not in list2]
7
8print("Elements in first list but not in second:", difference)

Output

Enter first list elements: 1 2 3 4
Enter second list elements: 3 4
Elements in first list but not in second: ['1', '2']

What's going on

We iterate over the first list and keep only those elements that do not appear in the second list.