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
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.

After this program

If the idea is still fuzzy, read Day 5: Lists and List Methods in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 list programs, or see every topic on Python exercises.