Last Updated : 19 Feb, 2025
We are given three lists we need to find common elements in all three lists using sets. For example a = [1, 2, 3, 4], b = [2, 3, 5, 6] and c = [1, 2, 3, 7]. We need to find all common elements so that resultant output should be {2, 3}.
Using set.intersection()set.intersection() method finds common elements between multiple sets by returning a new set containing only elements present in all sets. It efficiently identifies shared elements across any number of sets.
Python
a = [1, 2, 3, 4]
b = [2, 3, 5, 6]
c = [1, 2, 3, 7]
# Convert lists to sets and find common elements
res = set(a).intersection(b, c)
print(f"Common elements: {res}")
Common elements: {2, 3}
Explanation:
& operator performs a set intersection in Python returning a set containing only elements that are common to all sets involved. It is a shorthand for intersection() method providing same result.
Python
a = [1, 2, 3, 4]
b = [2, 3, 5, 6]
c = [1, 2, 3, 7]
# Convert lists to sets and use the & operator
res = set(a) & set(b) & set(c)
print(f"Common elements: {res}")
Common elements: {2, 3}
Explanation:
Set comprehension allows the creation of a set by iterating over a sequence and applying a condition or transformation. It provides a concise way to build a set while filtering or modifying elements during iteration.
Python
a = [1, 2, 3, 4]
b = [2, 3, 5, 6]
c = [1, 2, 3, 7]
# Set comprehension to find common elements
res = {x for x in a if x in b and x in c}
print(f"Common elements: {res}")
Common elements: {2, 3}
Explanation:
filter() function with a lambda allows filtering elements from a sequence based on a condition. It returns an iterator with elements that satisfy condition specified by lambda function.
Python
a = [1, 2, 3, 4]
b = [2, 3, 5, 6]
c = [1, 2, 3, 7]
# Filter common elements
res = set(filter(lambda x: x in b and x in c, a))
print(f"Common elements: {res}")
Common elements: {2, 3}
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4