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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 13 views 0 copies

Python code

16 lines
Python 3.9+
from 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

stdout
[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

  1. Use `functools.reduce` with `Counter` to apply intersection iteratively.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.