Python Program to Check if Two Lists Have Common Elements
bool(set(list1) & set(list2)), which returns True if there is any overlap and False otherwise.Examples
How to Think About It
Algorithm
Code
def have_common_elements(list1, list2): return bool(set(list1) & set(list2)) # Example usage list1 = [1, 2, 3] list2 = [3, 4, 5] print(have_common_elements(list1, list2))
Dry Run
Let's trace the example where list1 = [1, 2, 3] and list2 = [3, 4, 5] through the code.
Convert lists to sets
set(list1) = {1, 2, 3}, set(list2) = {3, 4, 5}
Find intersection
set(list1) & set(list2) = {3}
Check if intersection is not empty
bool({3}) = True
Return result
Function returns True
| Operation | Value |
|---|---|
| set(list1) | {1, 2, 3} |
| set(list2) | {3, 4, 5} |
| Intersection | {3} |
| Result | True |
Why This Works
Step 1: Convert lists to sets
Using set() removes duplicates and allows fast operations like intersection.
Step 2: Find intersection
The & operator finds common elements between two sets.
Step 3: Check if intersection is not empty
If the intersection set has any elements, bool() returns True, meaning lists share common items.
Alternative Approaches
def have_common_elements(list1, list2): for item in list1: if item in list2: return True return False print(have_common_elements([1, 2, 3], [3, 4, 5]))
def have_common_elements(list1, list2): return not set(list1).isdisjoint(set(list2)) print(have_common_elements([1, 2, 3], [3, 4, 5]))
Complexity: O(n + m) time, O(n + m) space
Time Complexity
Converting lists to sets takes O(n) and O(m) time, where n and m are list lengths. Intersection operation is O(min(n, m)). Overall, this is efficient for large lists.
Space Complexity
Extra space is used to store sets of size up to n and m, so O(n + m).
Which Approach is Fastest?
Using sets and intersection is faster than looping through lists because set operations are optimized for membership checks.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Set intersection | O(n + m) | O(n + m) | Large lists, fast checks |
| Loop with membership | O(n * m) | O(1) | Small lists, simple code |
| Set.isdisjoint() | O(n + m) | O(n + m) | Readable and efficient |