lassence.net

Get common elements between lists in Python

--- archive: codebook, 2020–2023 topic: Python ---

When you want to get the intersection (common elements) between two or more lists, an easy way in Python is to convert your lists to sets and use intersection().

Note that it will remove any duplicates, and only return unique elements.

# Two lists
a = ['apple', 'pear', 'orange', 'kiwi', 'banana', 'lemon']
b = ['melon', 'lemon', 'strawberry', 'kiwi']

# Get intersection
set(a).intersection(set(b))
{'kiwi', 'lemon'}

You can also get elements that are not common between the lists:

# Get difference
set(a).difference(set(b))
{'apple', 'banana', 'orange', 'pear'}
Subscribed, thanks. Your address is only used for this newsletter.