The Wayback Machine - https://web.archive.org/web/20240927122817/https://www.geeksforgeeks.org/python-intersection-two-lists/
Open In App

Python | Intersection of two lists

Last Updated : 09 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Intersection of two list means we need to take all those elements which are common to both of the initial lists and store them into another list. Now there are various ways in Python, through which we can perform the Intersection of the lists. 
Examples: 
 

Input : 
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]
Output :
[9, 10, 4, 5]

Input :
lst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]
lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]
Output :
[9, 11, 26, 28]


 


Method 1: 
This is the simplest method where we haven’t used any built-in functions. 
 

Python3
# Python program to illustrate the intersection
# of two lists in most simple way
def intersection(lst1, lst2):
    lst3 = [value for value in lst1 if value in lst2]
    return lst3

# Driver Code
lst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]
lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]
print(intersection(lst1, lst2))

Output: 
 

[9, 11, 26, 28]


Method 2: 
This method includes the use of set() method. 
 

Python3
# Python program to illustrate the intersection
# of two lists using set() method
def intersection(lst1, lst2):
    return list(set(lst1) & set(lst2))

# Driver Code
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]
print(intersection(lst1, lst2))

Output: 
 

[9, 10, 4, 5]

The time complexity of the above program is O(n), where n is the length of the longer list between lst1 and lst2.

The space complexity of the program is O(n), where n is the length of the smaller list between lst1 and lst2. 


Method 3: 
In this method we set() the larger list and then use the built-in function called intersection() to compute the intersected list. intersection() is a first-class part of set. 
 

Python3
# Python program to illustrate the intersection
# of two lists using set() and intersection()
def Intersection(lst1, lst2):
    return set(lst1).intersection(lst2)
    
# Driver Code
lst1 = [ 4, 9, 1, 17, 11, 26, 28, 28, 26, 66, 91]
lst2 = [9, 9, 74, 21, 45, 11, 63]
print(Intersection(lst1, lst2))

Output: 
 

{9, 11}


Method 4: 
By the use of this hybrid method the complexity of the program falls to O(n). This is an efficient way of doing the following program. 
 

Python3
# Python program to illustrate the intersection
# of two lists
def intersection(lst1, lst2):

    # Use of hybrid method
    temp = set(lst2)
    lst3 = [value for value in lst1 if value in temp]
    return lst3

# Driver Code
lst1 = [9, 9, 74, 21, 45, 11, 63]
lst2 = [4, 9, 1, 17, 11, 26, 28, 28, 26, 66, 91]
print(intersection(lst1, lst2))

Output: 
 

[9, 9, 11]


Method 5: 
This is the where the intersection is performed over sub-lists inside other lists. Here we have used the concept of filter(). 
 

Python3
# Python program to illustrate the intersection
# of two lists, sublists and use of filter()
def intersection(lst1, lst2):
    lst3 = [list(filter(lambda x: x in lst1, sublist)) for sublist in lst2]
    return lst3

# Driver Code
lst1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
lst2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
print(intersection(lst1, lst2))

Working: The filter part takes each sublist’s item and checks to see if it is in the source list. The list comprehension is executed for each sublist in list2. 
Output: 
 

[[13, 32], [7, 13, 28], [1, 6]]

Method 6: Using reduce():
Algorithm:

  1. Import the reduce function from functools module.
  2. Define two lists.
  3. Initialize the variable intersection with an empty list.
  4. Use the reduce function to iterate over the elements of lst1.
  5. Inside the lambda function, check if the current element is present in lst2 and not already present in the intersection list.
  6. If it is, then add the current element to the intersection list.
  7. Return the intersection list.
  8. Print the intersection list.
Python
from functools import reduce

lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]

intersection = reduce(lambda acc, x: acc + [x] if x in lst2 and x not in acc else acc, lst1, [])

print(intersection)
#This code is contributed by Rayudu.

Output
[9, 10, 5, 4]

Time Complexity: O(n^2), where n is the length of lst1.
Space Complexity: O(n), where n is the length of lst1.

Python | Intersection of two lists – FAQs


How Do You Use Two Lists in Python? 

Using two lists in Python can be done in various ways depending on the task at hand. Common operations include iterating over both lists simultaneously, combining them, or performing set operations. For simultaneous iteration, you can use the zip() function, which pairs elements from two lists together in a tuple for each iteration.

Example of Using zip():

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
for number, letter in zip(list1, list2):
print(f"{number}: {letter}")

How to Create a Set from Two Lists in Python?

To create a set from two lists, which effectively combines the elements of both lists and removes duplicates, you can use set operations.

Example:

list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
combined_set = set(list1).union(list2)
print(combined_set) # Output: {1, 2, 3, 4, 5, 6}

How Do You Check if Two Lists Intersect in Python?

To check if two lists intersect (i.e., have common elements), you can use set operations. Here’s how you can find the intersection of two lists:

Example:

list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
intersection = set(list1).intersection(list2)
if intersection:
print("The lists intersect.")
else:
print("The lists do not intersect.")

How to Take Two Lists as Input in Python?

To take two lists as input in Python, you can prompt the user to enter the elements separated by a space and then use the split() method to convert the inputs into lists.

Example:

list1 = input("Enter elements of the first list separated by space: ").split()
list2 = input("Enter elements of the second list separated by space: ").split()
print("List 1:", list1)
print("List 2:", list2)

How Do You Write Multiple Lists in Python?

Writing multiple lists in Python can refer to creating multiple list variables or writing them to a file. If you mean creating them, simply define each list with its elements. If you mean writing to a file, you can iterate through each list and write its elements to a file.

Example of Writing Lists to a File:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
with open('lists.txt', 'w') as file:
for item in list1:
file.write(f"{item}\n")
for item in list2:
file.write(f"{item}\n")


Similar Reads

Intersection of two arrays in Python ( Lambda expression and filter function )
Given two arrays, find their intersection. Examples: Input: arr1[] = [1, 3, 4, 5, 7] arr2[] = [2, 3, 5, 6] Output: Intersection : [3, 5] We have existing solution for this problem please refer Intersection of two arrays link. We will solve this problem quickly in python using Lambda expression and filter() function. Implementation: C/C++ Code # Fun
1 min read
Python | Intersection of two String
One of the string operations can be computing the intersection of two strings i.e, output the common values that appear in both the strings. There are various ways in Python, through which we can perform the Intersection of two strings. Method #1 : Naive Method Create an empty string and check for new occurrence of character common to both string a
3 min read
Python | Intersection of two nested list
This particular article aims at achieving the task of intersecting two list, in which each element is in itself a list. This is also a useful utility as this kind of task can come in life of programmer if he is in the world of development. Lets discuss some ways to achieve this task. Method 1: Naive Method This is the simplest method to achieve thi
5 min read
Intersection of two dataframe in Pandas - Python
Intersection of Two data frames in Pandas can be easily calculated by using the pre-defined function merge(). This function takes both the data frames as argument and returns the intersection between them. Syntax: pd.merge(df1, df2, how) Example 1: import pandas as pd # Creating Data frames df1 = {'A': [1, 2, 3, 4], 'B': ['abc', 'def', 'efg', 'ghi'
1 min read
Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples: Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG Output : Possible Input : s1 = Hello : s2 = dnaKfhelddf Output : Not Possible Input : s1 = GeeksforGeeks : s2 = rteksfoGrdsskGeggehes Outpu
2 min read
Python set operations (union, intersection, difference and symmetric difference)
This article demonstrates different operations on Python sets. Examples: Input : A = {0, 2, 4, 6, 8} B = {1, 2, 3, 4, 5} Output : Union : [0, 1, 2, 3, 4, 5, 6, 8] Intersection : [2, 4] Difference : [8, 0, 6] Symmetric difference : [0, 1, 3, 5, 6, 8] In Python, below quick operands can be used for different operations. | for union. & for interse
1 min read
Intersection() function Python
Python set intersection() method returns a new set with an element that is common to all set The intersection of two given sets is the largest set, which contains all the elements that are common to both sets. The intersection of two given sets A and B is a set which consists of all the elements which are common to both A and B. Python Set intersec
2 min read
Python | Pandas TimedeltaIndex.intersection
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.intersection() function return a new Index with elements from the index that are common to both the indexes. This
2 min read
Python | Pandas Index.intersection()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.intersection() function form the intersection of two Index objects. This returns a new Index with elements common to the in
2 min read
Python | Sympy Line.intersection() method
In Sympy, the function intersection() is used to find the intersection with another geometrical entity. Syntax: Line.intersection(o) Parameters: o: Point or LinearEntity Returns: intersection: list of geometrical entities Example #1: # import sympy and Point, Line from sympy import Point, Line p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7) l1 =
1 min read
Python – Sympy Polygon.intersection() Method
In Sympy, the function Polygon.intersection() is used to get the intersection of a given polygon and the given geometry entity. The geometry entity can be a point, line, polygon, or other geometric figures. The intersection may be empty if the polygon and the given geometry entity are not intersected anywhere. But can contain individual Points or c
2 min read
Most Efficient Way To Find The Intersection Of A Line And A Circle in Python
To make an efficient algorithm to find the intersection of a line and a circle, we need to understand what lines and circles are and how we can mathematically represent and calculate them in Python. Prerequisites LineCirclesQuadratics EquationsSolving a Quadratic EquationQuadratic Formula/Sridharacharya FormulaMathematical ApproachTo find the inter
8 min read
Creating a sorted merged list of two unsorted lists in Python
We need to take two lists in Python and merge them into one. Finally, we display the sorted list. Examples: Input : list1 = [25, 18, 9, 41, 26, 31] list2 = [25, 45, 3, 32, 15, 20] Output : [3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45] Input : list1 = ["suraj", "anand", "gaurav", "aman", "kishore"] list2 = ["rohan", "ram", "mohan", "priya", "komal"
1 min read
Python | Union of two or more Lists
Union of a list means, we must take all the elements from list A and list B (there can be more than two lists) and put them inside a single new list. There are various orders in which we can combine the lists. For e.g., we can maintain the repetition and order or remove the repeated elements in the final list and so on. Examples: Maintained repetit
7 min read
Python | Check if two lists have at-least one element common
Given two lists a, b. Check if two lists have at least one element common in them. Examples: Input : a = [1, 2, 3, 4, 5] b = [5, 6, 7, 8, 9] Output : True Input : a=[1, 2, 3, 4, 5] b=[6, 7, 8, 9] Output : FalseMethod 1: Traversal of List Using traversal in two lists, we can check if there exists one common element at least in them. While traversing
5 min read
Python | Check whether two lists are circularly identical
Given two lists, check if they are circularly identical or not. Examples: Input : list1 = [10, 10, 0, 0, 10] list2 = [10, 10, 10, 0, 0] Output : Yes Explanation: yes they are circularly identical as when we write the list1 last index to second last index, then we find it is circularly same with list1 Input : list1 = [10, 10, 10, 0, 0] list2 = [1, 1
5 min read
Python | Print all the common elements of two lists
Given two lists, print all the common elements of two lists. Examples: Input : list1 = [1, 2, 3, 4, 5] list2 = [5, 6, 7, 8, 9] Output : {5} Explanation: The common element of the lists is 5. Input : list1 = [1, 2, 3, 4, 5] list2 = [6, 7, 8, 9] Output : No common elements Explanation: They do not have any elements in common in between them Method 1:
8 min read
Python | Find missing and additional values in two lists
Given two lists, find the missing and additional values in both the lists. Examples: Input : list1 = [1, 2, 3, 4, 5, 6] list2 = [4, 5, 6, 7, 8] Output : Missing values in list1 = [8, 7] Additional values in list1 = [1, 2, 3] Missing values in list2 = [1, 2, 3] Additional values in list2 = [7, 8] Explanation: Approach: To find the missing elements o
3 min read
Python | Check if two lists are identical
This article deals with the task of ways to check if two unordered list contains exact similar elements in exact similar position, i.e to check if two lists are exactly equal. This is quite a useful utility and can be used in day-day programming. Method 1: Using list.sort() and == operator sort() coupled with == operator can achieve this task. We f
7 min read
Python | Extract Combination Mapping in two lists
Sometimes, while working with Python lists, we can have a problem in which we have two lists and require to find the all possible mappings possible in all combinations. This can have possible application in mathematical problems. Let's discuss certain way in which this problem can be solved. Method : Using zip() + product() With these functions thi
2 min read
How to Concatenate Two Lists Index Wise in Python
Index-wise concatenation of two lists refers to adding or combining elements of the given list based on their indices. There are many real-world applications of concatenating two lists index-wise, such as data processing, string manipulation, generating composite keys or super keys(in the database), and so on. In this article, we are going to deep
4 min read
Merge Two Lists in Python
Let's see how to concatenate two lists using different methods in Python. This operation is useful when we have a number of lists of elements that need to be processed in a similar manner. Input: test_list1 = [1, 4, 5, 6, 5] test_list2 = [3, 5, 7, 2, 5]Output: [1, 4, 5, 6, 5, 3, 5, 7, 2, 5]Explanation: The output list is the list we get from Mergin
7 min read
Python | Difference between two lists
In Python programming, comparing two lists is a common task with multiple approaches. This article explores different methods for obtaining the dissimilarity between two lists, enhancing your proficiency in handling lists and data comparison in Python. Join us on this insightful journey into various strategies for discerning differences between lis
6 min read
Python | Convert two lists into a dictionary
Interconversion between data types is usually necessary for real-time applications as certain systems have certain modules that require input in a particular data type. Let's discuss a simple yet useful utility of conversion of two lists into a key: value pair dictionary in Python. Converting Two Lists into a DictionaryPython List is a sequence dat
11 min read
Find common elements in three sorted arrays by dictionary intersection
One way to efficiently find shared items in three sorted arrays is by using dictionary intersection. However, it's important to note that dictionaries are commonly used for unique keys, so if there are duplicate elements in your arrays, some adjustments may be needed to make this approach work. Given three arrays sorted in non-decreasing order, pri
4 min read
Python | Set 3 (Strings, Lists, Tuples, Iterations)
In the previous article, we read about the basics of Python. Now, we continue with some more python concepts. Strings in Python: A string is a sequence of characters that can be a combination of letters, numbers, and special characters. It can be declared in python by using single quotes, double quotes, or even triple quotes. These quotes are not a
3 min read
Python | Maximum sum of elements of list in a list of lists
Given lists in a list, find the maximum sum of elements of list in a list of lists. Examples: Input : [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]] Output : 33 Explanation: sum of all lists in the given list of lists are: list1 = 6, list2 = 15, list3 = 33, list4 = 24 so the maximum among these is of Input : [[3, 4, 5], [1, 2, 3], [0, 9, 0]] Outpu
4 min read
Python | Iterate over multiple lists simultaneously
Iterating over single lists, refers to using for loops for iteration over a single element of a single list at a particular step whereas in iterating over multiple lists simultaneously, we refer using for loops for iteration over a single element of multiple lists at a particular step. Iterate over multiple lists at a time For better understanding
4 min read
Python | Create a Pandas Dataframe from a dict of equal length lists
Given a dictionary of equal length lists, task is to create a Pandas DataFrame from it. There are various ways of creating a DataFrame in Pandas. One way is to convert a dictionary containing lists of equal lengths as values. Let's discuss how to create a Pandas Dataframe from a dict of equal length lists with help of examples. Example #1: Given a
2 min read
Python | Ways to create a dictionary of Lists
Till now, we have seen the ways to create a dictionary in multiple ways and different operations on the key and values in the Python dictionary. Now, let's see different ways of creating a dictionary of lists. Note that the restriction with keys in the Python dictionary is only immutable data types can be used as keys, which means we cannot use a d
6 min read
Practice Tags :