PYTHON
Efficiently Find Common Elements in Two Lists
Discover how to quickly find all shared elements between two Python lists using set operations for optimal performance, ideal for data comparison.
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
# Convert lists to sets for efficient intersection
common_elements = list(set(list1).intersection(set(list2)))
print(f"List 1: {list1}")
print(f"List 2: {list2}")
print(f"Common Elements: {common_elements}")
# Example with strings
fruits1 = ["apple", "banana", "cherry", "date"]
fruits2 = ["banana", "elderberry", "fig", "date"]
common_fruits = list(set(fruits1).intersection(set(fruits2)))
print(f"Common Fruits: {common_fruits}")
How it works: This snippet demonstrates how to find common elements between two lists efficiently. By converting the lists to sets, the `intersection()` method can be used, which offers fast lookup and O(min(len(s1), len(s2))) performance, making it much quicker than iterating through nested loops for larger lists. The result is then converted back to a list.