Python | Intersection of two lists
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. Show
Recommended: Please try your approach on {IDE} first, before moving on to the solution. Method 1: Python3
Output: Method 2: Python3
Output: Method 3: Python3
Output: Method 4: Python3
Output: Method 5: Python3
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. Article Tags : Python Python list-programs python-list Practice Tags : python-list Python Program to Find Intersection of Two ListsIn this tutorial, we will discuss how we can get the intersection of the two lists. The intersection of two lists means we need to get all the familiar elements to both of the initial lists. Python is known for its excellent built-in data structure. Python list is one of the famous and valuable built-in data types of Python. It can store the various data-types value in sorted order. However, there is no built-in function for lists like sets. Python provides the many ways to perform the intersection of the lists. Let's see the following scenario. Input : Output: [90, 11, 58, 31, 66, 28, 54] Input : Output: [9, 11, 26, 28] Let's see following methods to get intersection of two lists. Method - 1: Using for loopOutput: [90, 11, 58, 31, 66, 28, 54] We have used for loop to get the common value from both lists and stored it in the list3 variable. Method - 2: Convert List to SetOutput: [66, 90, 11, 54, 58, 28, 31] Method - 3:We will use the built-in set's intersection() method. The intersection() is a first-class part of the set. Let's understand the following example. Example - Output: {66, 90, 11, 54, 58, 28, 31} Method - 4:In this method, we will use the hybrid method. This is much efficient way to perform the task. Let's understand the following example. Example - Output: [90, 11, 58, 31, 66, 28, 54] Method - 5:In this method, we will use the filter() method. The intersection is performed over sub-lists inside other lists. Let's understand the following example. Example - Output: [[17, 23, 40], [10], [60]] The filter() method takes each item of the sublist and checks if it is present in the list1. The list comprehension is executed for each sublist in the list2. Next TopicHow to Create Requirements.txt File in Python ← prev next → What is intersection?An intersection in python can be performed between two or more lists or sets. With intersection, we get the common elements present in all the lists, i.e., it returns the elements which exist in all the lists. Example : If we have two lists – A and B containing the following elements: A = [0,1,10,5,8] B = [7,1,3,11,0] Then here, there are only two common elements from both the list – 0 and 1. Therefore, the intersection between the two lists would be 0 and 1. Performing Python List IntersectionNow, we shall look into some methods of intersecting lists in python:
Find the intersection of two lists in PythonIn this post, you will learn different ways to find the intersection of two lists in Python. The intersection of two lists contains the elements that the two lists have in common. The returned list contains only items that exist in both lists, or in all lists, if the comparison is done with more than two lists. There are various ways through which we can perform the intersection of two lists. Here we have mentioned most of them - Using sets to find intersection of two lists in PythonThe first method to find the intersection of two lists in Python is to convert the lists to sets and use either the & operator or the built-in intersection() method. 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 & operator or the intersection() method. 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 – list1 and list2 – on lines 1 and 2. Next, on lines 4 and 5, we use the set() function to convert the lists to sets. On line 7, we use the & operator to find the intersection between the two sets. This operator returns a new set with elements common to both set1 and set2. We pass this resulting set to the list() function to convert it back to a list and assign the resulting list to intersect. Finally, we print the value of intersect on line 9. 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 intersection() method. While the & operator can only be used on two sets, the intersection() method can be used with other types of iterables, such as a list or tuple. Its syntax is as follows: <name of set>.intersection(<names of interables>)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 list1 to a set. This is because we can pass a list (e.g. list2) directly to the intersection() method, without having to convert the list to a set. We do that on line 6, where we use set1 to call the intersection() method and pass list2 as an argument to the method. This method returns a set. We convert the set back to a list using the list() function, and assign the result to intersect. Finally, we print the value of intersect on line 8. 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 <module> set1 = set(list1) TypeError: unhashable type: 'list'Using a Python For Loop to Find Intersection Between Two ListsUsing a Python for loop is an easy, intuitive way to find the intersection between two lists. The benefit of understandability here comes at a performance hit with lists of much larger sizes. What we’ll do, is loop over each item in a list and see if it exists in the other. If it does, then we append it to a new list. If it doesn’t, then we’ll do nothing. Let’s take a look at what this code would look like: # Find intesection between two Python lists using a for loop list1 = ['a', 'b', 'c', 'd', 'e'] list2 = ['b', 'd', 'e', 'f', 'g'] intersection = list() for item in list1: if item in list2: intersection.append(item) print(intersection) # Returns: ['b', 'd', 'e']In the next section, you’ll learn how to turn this for loop into a Python list comprehension. Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here. Using List Comprehensions to find the Intersection Between Two Python ListsIn many cases, a Python for loop can be turned into a list comprehension. The benefit of doing this is the ease of coding it out. Python list comprehensions comes with some key benefits:
Essentially, the algorithm we’ll follow is the same as the for loop: we loop over each item and see if it exists in the other list. If it does, then we add it to our new list. Let’s see what this would look like in Python: # Find intesection between two Python lists using a list comprehension list1 = ['a', 'b', 'c', 'd', 'e'] list2 = ['b', 'd', 'e', 'f', 'g'] intersection = [item for item in list1 if item in list2] print(intersection) # Returns: ['b', 'd', 'e']Similar to the for loop method, as your list sizes grow, this can encounter some performance hiccups. This is where the next method comes into play. In the next section, you’ll learn how to use Python set methods to find the intersection between two lists. Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here. How to find the intersection of two list elements in python |