PYTHON

Find Common Elements Across Multiple Lists Using Sets

Discover elements present in all given lists efficiently using Python's set intersection operations, a powerful technique for data comparison and filtering in web applications.

# Example 1: Finding common elements in three lists
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
list3 = [5, 6, 7, 8, 9]

# Convert lists to sets for efficient intersection
set1 = set(list1)
set2 = set(list2)
set3 = set(list3)

common_elements = set1.intersection(set2, set3)
print(f"Common elements across list1, list2, list3: {sorted(list(common_elements))}")
# Expected: [5]

# Example 2: Finding common words in multiple sentences
sentence1_words = "The quick brown fox jumps over the lazy dog".split()
sentence2_words = "A quick brown cat runs under the table".split()
sentence3_words = "The quick red fox barks loudly".split()

common_words = set(sentence1_words).intersection(set(sentence2_words), set(sentence3_words))
print(f"
Common words across sentences: {sorted(list(common_words))}")
# Expected: ['brown', 'quick', 'the'] (case-sensitive)

# Example 3: Generalizing for an arbitrary number of lists
all_lists = [
    [10, 20, 30, 40],
    [20, 30, 50, 60],
    [30, 40, 50, 70],
    [30, 80, 90]
]

# Start with the set of the first list, then intersect with the rest
if all_lists:
    common_across_all = set(all_lists[0])
    for lst in all_lists[1:]:
        common_across_all = common_across_all.intersection(set(lst))
    print(f"
Common elements across all lists: {sorted(list(common_across_all))}")
else:
    print("
No lists provided.")
# Expected: [30]
How it works: To efficiently find common elements across multiple lists, converting them to sets is the most performant approach in Python. Sets are unordered collections of unique elements and provide highly optimized methods for mathematical set operations like `intersection()`. By converting each list to a set and then calling `intersection()` with all other sets as arguments, you can quickly determine which elements are present in every single list, avoiding slower nested loop comparisons.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs