Finding the intersection of two lists in Python can be done using the set()
function or list comprehension. Here are two examples:
Example 1:
list1 = [1, 2, 3, 4, 5] list2 = [4, 5, 6, 7, 8] intersection = list(set(list1) & set(list2)) print(f"The intersection of list1 and list2 is: {intersection}")
Output:
The intersection of list1 and list2 is: [4, 5]
Example 2:
fruits1 = ['apple', 'banana', 'orange'] fruits2 = ['orange', 'kiwi', 'melon'] intersection = [fruit for fruit in fruits1 if fruit in fruits2] print(f"The intersection of fruits1 and fruits2 is: {intersection}")
Output:
The intersection of fruits1 and fruits2 is: [‘orange’]