HomePythonPython Program to Find the Intersection of Two Lists

Python Program to Find the Intersection of Two Lists


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.

Problem Statement

You are given two lists, list1 and 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

  1. The lists list1 and list2 are defined.
  2. A list comprehension is used to iterate through each element (value) in list1.
  3. For each element in list1, the condition if value in list2 is checked. This condition verifies if the element is also present in list2.
  4. If the condition is true, the element is added to the intersection list.
  5. After the list comprehension completes, the intersection list contains all the elements that are common to both list1 and list2.

Input/ Output

Python Program to Find the Intersection of Two Lists

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...