How to find the intersection between two lists in Python
Created
Modified
Using Set Intersection
A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
#!/usr/bin/python3
# -*- coding: utf8 -*-
l1 = ["a", "b", "c"]
l2 = ["b", "a", "C"]
lst = list(set(l1) & set(l2))
print(lst)
# Sets
A = {"a", "b", "c"}
B = {"b", "a", "C"}
# A & B
print(A & B)
# B & A
print(B & A)
['b', 'a'] {'b', 'a'} {'b', 'a'}
This will remove the duplicates in each list.
Using intersection Method
Return a new set with elements common to the set and all others. For example,
#!/usr/bin/python3
# -*- coding: utf8 -*-
l1 = ["a", "b", "c"]
l2 = ["b", "a", "C"]
lst = list(set(l1).intersection(l2))
print(lst)
['b', 'a']
Using List Comprehension
If you want to preserve order of input list, try this:
#!/usr/bin/python3
# -*- coding: utf8 -*-
a = ["a", "b", "c"]
b = ["b", "a", "C"]
# for loop
s = set(b)
lst = [x for x in a if x in s]
print(lst)
['a', 'b']
This is an O(n) solution, faster than O(n*m) performance.
Using lambda Operator
It can be achieved using filter and lambda operator. For example,
#!/usr/bin/python3
# -*- coding: utf8 -*-
a = ["a", "b", "c"]
b = ["b", "a", "C"]
# for loop
lst = list(filter(lambda x:x in a, b))
print(lst)
['b', 'a']