Find Common Elements in List of Lists in Python
Return elements that appear in every sublist of a nested list, preserving duplicates with Counter intersection.
Python code
16 linesfrom collections import Counter
def common_elements(list_of_lists):
"""Return elements present in every sublist."""
if not list_of_lists:
return []
counts = Counter(list_of_lists[0])
for sublist in list_of_lists[1:]:
counts &= Counter(sublist)
return list(counts.elements())
if __name__ == "__main__":
data = [[1, 2, 3, 4], [2, 4, 6, 8], [2, 3, 4, 5]]
print(common_elements(data)) # Output: [2, 4]
Output
[2, 4]
How it works
The function uses Counter to count element frequencies in the first sublist, then intersects it with each subsequent sublist's Counter using the & operator. The intersection keeps the minimum counts, so duplicates are preserved correctly. Converting the result back to a list with elements() yields all shared elements. The edge case of an empty input returns an empty list immediately. This approach is efficient and readable for typical data sizes.
Common mistakes
- Forgetting that `&` on Counters keeps only keys present in both, which is correct for intersection but can be confused with union.
- Not handling the empty list case, leading to an error when accessing `list_of_lists[0]`.
- Using `set` intersection without considering duplicates, which would incorrectly drop repeated elements.
Variations
- Use `functools.reduce` with `Counter` to apply intersection iteratively.
- Convert to sets if uniqueness is sufficient: `set.intersection(*(map(set, list_of_lists)))`.
Real-world use cases
- Finding common tags across different user profiles in a recommendation system.
- Identifying shared product IDs in multiple warehouse inventories for cross-stock checks.
- Extracting common interests from survey data to segment users for targeted marketing.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.