Finding the intersection of three lists in Python can be accomplished in several ways. A straightforward approach involves utilizing built-in data structures like sets, which allow for efficient membership testing and elimination of duplicates. Below is a Python function that takes three lists as input and returns a list containing the elements that are common to all three lists.
def intersect_three_lists(list1, list2, list3):
"""
Returns the intersection of three lists.
Parameters:
list1 (list): The first list.
list2 (list): The second list.
list3 (list): The third list.
Returns:
list: A list containing elements that are present in all three input lists.
"""
# Convert lists to sets to find intersection
set1 = set(list1)
set2 = set(list2)
set3 = set(list3)
# Find intersection of the three sets
intersection = set1.intersection(set2).intersection(set3)
# Convert the intersection set back to a list before returning
return list(intersection)
# Example usage:
list_a = [1, 2, 3, 4, 5]
list_b = [4, 5, 6, 7]
list_c = [5, 8, 9, 4]
result = intersect_three_lists(list_a, list_b, list_c)
print(result) # Output: [4, 5]
Explanation of the Function:
1. Function Definition: intersect_three_lists takes three lists as parameters.
2. Set Conversion: Each list is converted to a set. This step is crucial as sets automatically handle duplicates and provide fast membership testing.
3. Finding Intersection: The intersection of the three sets is calculated using the intersection() method, which is applied sequentially.
4. Returning the Result: The resulting set is converted back to a list before being returned for consistency with the input type.
Performance Consideration:
Using sets is generally efficient for this task due to average-case time complexity of O(1) for membership checks and O(n) for constructing a set from a list, making it suitable for larger datasets.
This function is versatile and can handle any type of list elements; however, it is important to note that all elements in the lists must be hashable, as that is a requirement for set operations in Python.