Cover Image for Python Program to Find Intersection of Two Lists
199 views

Python Program to Find Intersection of Two Lists

To find the intersection of two lists in Python, you can use various methods, including list comprehensions, built-in functions, or sets. Here are a few examples:

Using List Comprehension:

You can use list comprehensions to create a new list containing elements that are common to both input lists:

list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]

intersection = [value for value in list1 if value in list2]

print(intersection)

This code will output [3, 4, 5], which is the intersection of list1 and list2.

Using the set Data Type:

You can convert the lists to sets and then use the intersection() method to find their intersection:

list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]

set1 = set(list1)
set2 = set(list2)

intersection = list(set1.intersection(set2))

print(intersection)

This code produces the same output: [3, 4, 5].

Using filter() and lambda:

You can use the filter() function along with a lambda function to find the intersection:

list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]

intersection = list(filter(lambda x: x in list1, list2))

print(intersection)

Again, this code yields [3, 4, 5].

Choose the method that best suits your needs and coding style. The first method using list comprehension is concise and readable, making it a popular choice for finding the intersection of two lists.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS