How do you find the intersection of two lists in python?
In this article, we are going to see how to intersect two lists that contain multiple lists in different ways. Let's start in the traditional way. Show
Follow the below the steps to solve the problem
ExampleLive Demo # initializing the lists list_1 = [[1, 2], [3, 4], [5, 6]] list_2 = [[3, 4]] # finding the common items from both lists result = [sub_list for sub_list in list_1 if sub_list in list_2] # printing the result print(result) If you run the above code, then you will get the following result. Output[[3, 4]] We'll use the set to intersect two lists. Follow the below steps.
ExampleLive Demo # initializing the lists list_1 = [[1, 2], [3, 4], [5, 6]] list_2 = [[3, 4]] # converting each sub list to tuple for set support tuple_1 = map(tuple, list_1) tuple_2 = map(tuple, list_2) # itersection result = list(map(list, set(tuple_1).intersection(tuple_2))) # printing the result print(result) If you run the above code, then you will get the following result. Output[[3, 4]] ConclusionIf you have any queries in the article, mention them in the comment section.
Updated on 13-Nov-2020 19:08:20
There are three main methods to find the intersection of two lists in Python:
This post explains the code for each method and discusses various factors to consider when deciding which method to use. For our practice question, we’ll work on a function that finds the intersection of two lists with duplicate items in each list.
For instance, if we pass the lists Table of Contents
The first method to find the intersection of two lists in Python is to convert the lists to sets and use either the But first, what is a set? A set is similar to a list, in that it can be used to store a collection of items (such as a collection of numbers). For instance, we can create a set to store the numbers 1, 22, 43, 64 and 57. To do that, we use curly braces, as shown in the example below: mySet = {1, 22, 43, 64, 57} As you can see, creating a set is very similar to creating a list, except that the former uses curly braces while the latter uses square brackets. A set is indeed very similar to a list. However, there are a few key differences between them, as explained in the table below: Key differences between a set and a list
To find the intersection of two lists in Python, we can
convert the lists to sets and use the built-in Let’s look at some examples: Converting lists to sets and using the & operatorlist1 = [1, 2, 3, 4, 5] list2 = [3, 4, 5, 6, 7] set1 = set(list1) set2 = set(list2) intersect = list(set1 & set2) print(intersect) Here, we first declare two lists – Next, on lines 4 and 5, we use the On line 7, we use the Finally, we print the value of If you run the code above, you’ll get the following output: [3, 4, 5] Converting lists to sets and using the intersection() methodNext, let’s look at an example that uses the While the Its syntax is as follows:
Let’s look at an example: list1 = [1, 2, 3, 4, 5] list2 = [3, 4, 5, 6, 7] set1 = set(list1) intersect = list(set1.intersection(list2)) print(intersect) Here, we only convert We do that on line 6, where we use This method returns a set. We convert the set back to a list using the Finally, we print the value of If you run the code above, you’ll get the following output: [3, 4, 5] Error in converting lists to setsLast but not least, let’s look at an example where we are unable to convert a list to a set. That happens when one or more of the items in the list is not hashable. For instance, if the list has a nested list (which is not hashable), we’ll get an error when we try to convert the list to a set. list1 = [1, 2, 3, 4, 5, [7, 8, 9]] set1 = set(list1) If you run the code above, you’ll get the following error: Traceback (most recent call last): File "...", line ..., in Using list comprehensionIn the previous section, we saw how we can convert
lists to sets and use the However, we also saw how that can fail when our lists contain unhashable items (such as a nested list). In cases like that, we can use list comprehension to find the intersection of two lists. This does not require us to convert any list to a set. To do that, we need to first understand how list comprehension works. If you are unfamiliar with list comprehension, you may want to refer to some previous posts, such as this and this. To recap, one possible way to use list comprehension is to use the following syntax: [ Using list comprehension to create a new intersection listSuppose we have two lists – If we want to add items in list1 = [1, 2, 3, 4] list2 = [3, 4, 5, 6] intersect = [x for x in list2 if x in list1] print(intersect) Line 4 in the code above says that for each item in If you run the code above, you’ll get the following output: [3, 4] This gives us the intersection of the two lists – Using list comprehension to find intersection of two lists with nested listsNext, let’s look at another example where the lists contain nested lists. list1 = [1, 2, [12, 5], [6, 7], 9, 10] list2 = [2, [6, 7], 15, 17] intersect2 = [x for x in list2 if x in list1] print(intersect2) If you run the code above, you’ll get the following output: [2, [6, 7]] This shows that list comprehension works even with nested lists. Using the built-in filter() functionLast but not least, let’s look at the third method to find the intersection of two lists in Python – using the The Suppose we have a list called numbers = [1, 2, 3, 4, 5, 6, 7, 8] If we want to filter all the even numbers in the list, we can define a function that returns We can then pass this function and the Let’s look at an example of how this works. numbers = [1, 2, 3, 4, 5, 6, 7, 8] def isEven(x): if x%2 == 0: return True even_numbers = list(filter(isEven, numbers)) print(even_numbers) print(numbers) Here, we first define the Next, we define a function called Next, we call the The We do that on line 7 and assign the resulting list to a variable called Finally, we print the values of If you run the code above, you’ll get the following output: [2, 4, 6, 8] [1, 2, 3, 4, 5, 6, 7, 8]
As mentioned previously, we can use the Using the filter() function to find intersection of two lists in Pythonlist1 = [1, 2, 3, 4] list2 = [3, 4, 5, 6] def intersectList1(x): if x in list1: return True intersect = list(filter(intersectList1, list2)) print(intersect) Here, we first
define a function called Next, we use the function to filter Finally, we print the value of the resulting list on line 10. If you run the code above, you’ll get the following output: [3, 4] Using the filter() function with a lambda functionNext, let’s look at one more example of using the list1 = [1, 2, 3, 4] list2 = [3, 4, 5, 6] intersect = list(filter(lambda x: x in list1, list2)) print(intersect) Here, the lambda function is lambda x: x in list1 The function evaluates the expression We pass this lambda function to the If you run the code above, you’ll get the following output: [3, 4] Not surprisingly, this example gives the same output as the preceding example as its lambda function does the same thing as the Which Method to Use?Now that we’ve covered three different methods to find the intersection of two lists in Python, let’s discuss some factors to consider when choosing which method to use. The first factor to consider is whether your list contains un-hashable items (such as a nested list). If it does, you’ll have to use either list comprehension or the Next, the second factor to consider is whether your list has duplicate items. If your list has duplicate items and you want the intersection to account for these items, none of the methods above is ideal. Let’s look at some examples: list1 = [1, 2, 3, 3, 5, 5, 6, 7, 8] list2 = [1, 3, 3, 3, 5, 6, 6, 9] # Example 1: Using sets set1 = set(list1) set2 = set(list2) intersect_1 = list(set1 & set2) intersect_2 = list(set1.intersection(list2)) print('Using sets') print(intersect_1) print(intersect_2) # Example 2: Using list comprehension intersect_3 = [x for x in list1 if x in list2] intersect_4 = [x for x in list2 if x in list1] print('Using list comprehension') print(intersect_3) print(intersect_4) # Example 3: Using filter() intersect_5 = list(filter(lambda x : x in list1, list2)) intersect_6 = list(filter(lambda x : x in list2, list1)) print('Using filter function') print(intersect_5) print(intersect_6) If you run the code above, you’ll get the following output: Using sets [1, 3, 5, 6] [1, 3, 5, 6] Using list comprehension [1, 3, 3, 5, 5, 6] [1, 3, 3, 3, 5, 6, 6] Using filter function [1, 3, 3, 3, 5, 6, 6] [1, 3, 3, 5, 5, 6] When we convert a list to a set, duplicate items are removed. For instance, if Therefore, in the first example above, when we convert Hence, we get Next, for the second example, notice that we get a different answer for This is because for This gives us different results as the result for In contrast, the result for The same difference in answers can be found
when we use the If we do not want such discrepancy in our answers, we’ll need to write our own function. This bring us to the practice question for today. Practice QuestionThe practice question for today is to write a function called The function finds the intersection of the two lists, based on the number of times an item appears in both lists. For instance, suppose we have the lists Although 1 appears three times in the second list, it only appears twice in the first. Hence, 1 appears twice in the intersection. Similarly, although 2 appears three times in the first list, it only appears once in the second. Hence, 2 appear once in the intersection. As you can see, the intersection is not based on the first or the second list. Instead, it is based on the number of times an item appears in both lists. Expected ResultsTo test your function, you can run the following statements: list1 = [1, 1, 2, 2, 2, 3] list2 = [1, 1, 1, 2, 3, 3, 4, 4] print(intersectWithDup(list1, list2)) list1 = [1, 2, 3, 4, 5, 5, 5] list2 = [2, 2, 2, 2, 3, 4, 7, 7, 8] print(intersectWithDup(list1, list2)) If you run the code above, you should get the following output: [1, 1, 2, 3] [2, 3, 4] HintsThere is more than one way to complete
the practice question for today. The suggested solution uses the You may want to refer to the following posts if you need help:
Suggested SolutionHere’s the suggested solution for today’s question: Click to see suggested solution from collections import Counter def intersectWithDup(list1, list2): a = Counter(list1) b = Counter(list2) set1 = set(list1) set2 = set(list2) list3 = list(set1 & set2) list4 = [] for i in list3: list4.extend([i]*min(a[i], b[i])) return list4 Here, we first import the Next, we define the Within the function, we pass A For instance, If we assign this object to a variable, say For instance, In our suggested solution, After we get this frequency, we are ready to find the intersection of the two lists. We first find the intersection without duplicates. To do that, we convert Next, we convert this intersection to a list and assign the resulting list to Next, we initialize an empty list called We then use a On line 15, For instance, suppose list1 = [1, 1, 2, 3] list2 = [1, 1, 1, 2, 2, 3]
The first time the
We then pass this list to
the We keep doing this until we finish iterating through all the items in When that happens, With that, the function is complete. How do you find the intersection in Python?How to Find the Intersection of Sets in Python?. 1) Using intersection() function.. 2) Using intersection operator(&). 3) Using empty set for set intersection.. Can we use intersection for list in Python?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.
How do you find the intersection of two tuples in Python?When it is required to find the intersection of data in tuple records, a list comprehension can be used. The list comprehension is a shorthand to iterate through the list and perform operations on it.
How do you intersect two arrays in Python?Practical Data Science using Python. Take two arrays A and B.. if length of A is smaller than length of B, then swap them.. calculate the frequency of elements in the array and store them into m.. for each element e in B, if e is present in m, and frequency is non-zero, decrease frequency m[e] by 1. ... . return the resultant array.. |