List Difference

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

PythonBeginner
Python
# Program to find list difference (A - B)

list1 = input("Enter first list elements: ").split()
list2 = input("Enter second list elements: ").split()

difference = [x for x in list1 if x not in list2]

print("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']

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