Last Updated : 10 Dec, 2024
Checking if two lists share at least one common element is a frequent task when working with datasets, filtering, or validating data. Python offers multiple efficient ways to solve this depending on the size and structure of the lists.
Usingset
Intersection
Converting both lists into sets and finding their intersection is the most efficient way to check for common elements especially for large lists.
Python
a = [1, 2, 3, 4]
b = [5, 6, 3, 8]
# Find common elements using set intersection
common = set(a) & set(b)
# Check if there are common elements
if common:
print("Common", common)
else:
print("Not common.")
Explanation:
set(a)
and set(b)
convert the lists into sets.&
operator finds the intersection of the two sets.Let's explore some other methods on how to check if two lists have at least one element in common
Usingany()
The any()
function efficiently checks for at least one match between two lists. This approach avoids creating sets and works well for small to medium-sized lists.
a = [1, 2, 3, 4]
b = [5, 6, 3, 8]
# Check for at least one common element
if any(item in b for item in a):
print("Common elements exist.")
else:
print("No common elements.")
Common elements exist.Explanation:
any()
stops execution as soon as a common element is found making it efficient.item in b for item in a
iterates over a
and checks for each element in b
.A simple nested loop can also check for common elements. The loop breaks early if a common element is found.
Python
a = [1, 2, 3, 4]
b = [5, 6, 3, 8]
# Check for common elements using nested loops
common = False
for i in a:
if i in b:
common = True
break
if common:
print("Common elements exist.")
else:
print("No common elements.")
Common elements exist.Explanation:
a
and checks for its presence in b
.filter()
and set()
Combining filter()
with set()
provides another clean way to find common elements. It’s efficient for functional programming scenarios.
The result is converted to a set to remove duplicates.
a = [1, 2, 3, 4]
b = [5, 6, 3, 8]
# Find common elements using filter and set
common = set(filter(lambda x: x in b, a))
if common:
print("Common", common)
else:
print("No common elements.")
Explanation:
filter()
checks each element of a
to see if it exists in b
.List comprehension can collect all the common elements but it is less efficient compared to set
operations when lists are large.
a = [1, 2, 3, 4]
b = [5, 6, 3, 8]
# Find common elements using list comprehension
common = [item for item in a if item in b]
if common:
print("Common", common)
else:
print("No common elements.")
Explanation:
a
and checks each element in b
.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