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 tutorial, you will learn how to Display Prime Numbers Between Two Intervals using the if and else...
In this python tutorial, you will learn how to Calculate Standard Deviation with built in functions of the python programming...
In this Python program, we will convert temperature values from Celsius to Fahrenheit. The Celsius and Fahrenheit scales are two...