This Python program demonstrates two methods to find the intersection of two lists. Finding the intersection of two lists is a common task in programming, especially when dealing with data analysis, sets, or filtering. The intersection of two lists consists of the elements that are present in both lists. In other words, it’s the set of values that are common to both lists.
You are given two lists,
list2, each containing integers. Your task is to write a Python program that finds and returns the intersection of these two lists. The intersection of two lists is defined as the set of elements that are present in both lists.
Python Program to Find the Intersection of Two Lists
def find_intersection(list1, list2): intersection = [value for value in list1 if value in list2] return intersection # Example lists list1 = [1, 2, 3, 4, 5] list2 = [3, 4, 5, 6, 7] intersection_result = find_intersection(list1, list2) print("Intersection of the two lists:", intersection_result)
How it Works
- The lists
- A list comprehension is used to iterate through each element (
- For each element in
list1, the condition
if value in list2is checked. This condition verifies if the element is also present in
- If the condition is true, the element is added to the
- After the list comprehension completes, the
intersectionlist contains all the elements that are common to both