Common elements comparison between 2 lists

list, python

Solution

Use Python's set intersection:

>>> list1 = [1,2,3,4,5,6]
>>> list2 = [3, 5, 7, 9]
>>> list(set(list1).intersection(list2))
[3, 5]

Problem

Given two input lists, how can I create a list of the elements that are common to both inputs? For example: for inputs `[1,2,3,4,5,6]` and `[3,5,7,9]`, the result should be `[3, 5]`; for inputs `['this','this','n','that']` and `['this','not','that','that']`, the result should be `['this', 'that']`. See also: - In Python, how do I find common words from two lists while preserving word order? (to keep the order) - Python -Intersection of multiple lists? (for computing the intersection between >= 3 lists) - Intersection of two lists including duplicates? (to keep the duplicate elements)

Original source

Related problems