Python Practice › List Programs › Program 32
Difference between two lists
Write a Python program to get the items in the first list that are not in the second.
Input
[1, 2, 3, 4, 5], [2, 4, 6]
Output
[1, 3, 5] [1, 3, 5, 6]
Approach
- Keep items of list1 not in list2.
Solution
a = [1, 2, 3, 4, 5]b = [2, 4, 6]print([x for x in a if x not in b])print(sorted(set(a) ^ set(b)))Output
[1, 3, 5] [1, 3, 5, 6]
Line by line
Line 3
Items only in a, in their original order.
Line 4
The symmetric difference gives items in exactly one of the lists.
Learn the concept
New to this topic? Read the lesson, then come back.