Home / Python / Example programs / Lists

Python program: Common elements of two lists

Find the items two lists share, and the ones they do not.

The code

a = [1, 2, 3, 4, 5]
b = [4, 5, 6, 7]
print(sorted(set(a) & set(b)))      # in both
print(sorted(set(a) | set(b)))      # in either
print(sorted(set(a) - set(b)))      # only in a
print([x for x in a if x in b])     # keeps a's order

Output

[4, 5]
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3]
[4, 5]

How it works

Convert to sets and use the set operators. The comprehension keeps the original order but is slower for big lists.

Python features used

Learn the ideas behind it in the free lesson Dictionaries & Sets.