{"id":16186,"date":"2021-11-11T15:47:13","date_gmt":"2021-11-11T10:17:13","guid":{"rendered":"https:\/\/java2blog.com\/?p=16186"},"modified":"2021-11-11T15:47:13","modified_gmt":"2021-11-11T10:17:13","slug":"list-intersection-in-python","status":"publish","type":"post","link":"https:\/\/java2blog.com\/list-intersection-in-python\/","title":{"rendered":"List intersection in python"},"content":{"rendered":"<p>A list is one of Python&#8217;s fundamental in-built data types and clusters several items in a single variable.<\/p>\n<p>In this article, we will demonstrate the different ways available to retrieve the list intersection in Python.<\/p>\n<h2>What is the list intersection in Python?<\/h2>\n<p>The intersection of two lists returns the elements that are present in both lists. There are several methods to find these elements.<\/p>\n<h2>Ways to find the list intersection in Python<\/h2>\n<h3>Using the <code>for<\/code> loop to achieve list intersection in Python<\/h3>\n<p>Instead of using any built-in functions available for this purpose, we can always create a simple user-defined function using the <code>for<\/code> loop.<\/p>\n<p>For example,<\/p>\n<pre code = \"Python\">\nX = [1,3,5,7,9]\nY = [1,5,10,15]\ndef intsec(A, B):\nintsec = []\nfor val in A:\nif val in B:\nintsec.append(val)\nprint(intsec)\nintsec(X,Y)\n<\/pre>\n<p>The above code provides the following output:<\/p>\n<div class=\"content-box-green\">\n    [1, 5]\n<\/div>\n<h5>Explanation<\/h5>\n<ul>\n<li>We first define two lists named <code>X<\/code> and <code>Y<\/code> in the above code.<\/li>\n<li>We create a user-defined function that uses the for loop to traverse the list and find the common elements.<\/li>\n<li>We store these elements in a new list <code>intsec<\/code> and display them.<\/li>\n<\/ul>\n<p>List comprehension can simplify the code and make the syntax compact in this case. <\/p>\n<p>For example,<\/p>\n<pre code = \"Python\">\nX = [1,3,5,7,9]\nY = [1,5,10,15]\nZ = [val for val in X if val in Y]\nprint(Z)\n<\/pre>\n<p>The above code provides the following output:<\/p>\n<div class=\"content-box-green\">\n    [1, 5]\n<\/div>\n<p>This method increases the program&#8217;s efficiency, dropping its complexity to <code>O(n)<\/code>.<\/p>\n<h3>Using the <code>set()<\/code> function to find list intersection in Python<\/h3>\n<p>We first convert the given lists into sets individually using the <code>set()<\/code> method. Then we apply the intersection on the two sets using the intersection <code>&amp;<\/code> operator, which returns the intersection between the two sets.<\/p>\n<p>See the code below.<\/p>\n<pre code = \"Python\">\nX = [1,3,5,7,9]\nY = [1,5,10,15]\nZ = list(set(X) & set(Y))\nprint(Z)\n<\/pre>\n<p>The above code provides the following output:<\/p>\n<div class=\"content-box-green\">\n    [1, 5]\n<\/div>\n<h5>Explanation<\/h5>\n<ul>\n<li>The two lists <code>X<\/code> and <code>Y<\/code> are defined.<\/li>\n<li>Both the lists are converted into sets using the <code>set()<\/code> method. <\/li>\n<li>We carry out the intersection operation using the <code>&amp;<\/code> operator.<\/li>\n<li>The result is stored in <code>Z<\/code> and is displayed.<\/li>\n<\/ul>\n<h3>Using the <code>intersection()<\/code> function to find list intersection in Python<\/h3>\n<p>Sets have an in-built method, <code>intersection()<\/code>, which can quickly get the common items between sets. The <code>intersection()<\/code> function will return the common values from both sets in a freshly generated set. <\/p>\n<p>The lists need to be explicitly converted into sets first, as done in the previous method to use this function.<\/p>\n<p>See the code below.<\/p>\n<pre code = \"Python\">\nX = [1,3,5,7,9]\nY = [1,5,10,15]\nZ = list(set(X).intersection(set(Y)))\nprint(Z)\n<\/pre>\n<p>The above code provides the following output:<\/p>\n<div class=\"content-box-green\">\n    [1, 5]\n<\/div>\n<h3>Using the <code>filter()<\/code> and <code>lambda<\/code> functions to find list intersection in Python<\/h3>\n<p>Python&#8217;s <code>filter()<\/code> function can filter out elements of a given list based on some condition. Only the elements that satisfy this condition will be returned by this function.<\/p>\n<p>Here, we will also take help from the <code>lambda<\/code> function. A lambda function is a single-expression, one-line function that can take any number of arguments.<\/p>\n<p>We use both these functions in the following example.<\/p>\n<pre code = \"Python\">\nX = [1,3,5,7,9]\nY = [1,5,10,15]\nZ = list(filter(lambda x:x in X,Y))\nprint(Z)\n<\/pre>\n<p>The above code provides the following output:<\/p>\n<div class=\"content-box-green\">\n    [1, 5]\n<\/div>\n<h5>Explanation<\/h5>\n<ul>\n<li>We create the two lists.<\/li>\n<li>The <code>filter()<\/code> function takes each item of the first list and compares it with the items in the second list to check whether it is present in both lists.<\/li>\n<li>If this is <code>True<\/code>, then we store the element in the list <code>Z<\/code>.<\/li>\n<\/ul>\n<p>The advantage of this method over its peers mentioned in this article is that we can also use it over sub-lists contained within the other lists.<\/p>\n<h3>Using the <code>Counter<\/code> class to find list intersection in Python<\/h3>\n<p>The <code>Counter<\/code> is a class from the <code>collections<\/code> module that keeps track of all the items&#8217; frequency of occurrence in a given iterable. We can use it to return the list intersection of two lists.  <\/p>\n<p>For example,<\/p>\n<pre code = \"Python\">\nfrom collections import Counter\nX = Counter([1,3,5,7,9])\nY = Counter([1,5,10,15])\nZ = X & Y\nZ = list(Z.elements())\nprint(Z)\n<\/pre>\n<p>The above code provides the following output:<\/p>\n<div class=\"content-box-green\">\n    [1, 5]\n<\/div>\n<h5>Explanation<\/h5>\n<ul>\n<li>We apply the <code>Counter()<\/code> constructor to both lists.<\/li>\n<li>We perform the intersection operation on both <code>X<\/code> and <code>Y<\/code> using the <code>&amp;<\/code> operator.<\/li>\n<li>We store the elements of this class in <code>Z<\/code> using the <code>elements()<\/code> function.<\/li>\n<li>Finally, we display the common elements.<\/li>\n<\/ul>\n<h3>Using the <code>numpy.intersect1d()<\/code> function to find list intersection in Python<\/h3>\n<p>The <code>numpy.intersect1d<\/code> function returns an array containing the intersection of two given arrays. We can convert this final result to a list using the <code>list()<\/code> function.<\/p>\n<p>For example,<\/p>\n<pre code = \"Python\">\n    import numpy as np\n    X = [1,3,5,7,9]\n    Y = [1,5,10,15]\n    Z = list(np.intersect1d(X, Y))\n    print(Z)\n<\/pre>\n<p>Output:<\/p>\n<div class=\"content-box-green\">\n    [1, 5]\n<\/div>\n<p>That&#8217;s all about list intersection in Python.<\/p>\n<section class=\"read-more-posts\">\n<div class=\"rm-header\">\n<h2>Further reading:<\/h2>\n<\/div>\n<div class=\"rm-wrap\">\n<div class=\"rm-item\">\n<h5><a href=\"https:\/\/java2blog.com\/find-common-elements-in-two-lists-python\/\" target=\"_blank\" rel=\"noopener\">Find common elements in two list in Python<\/a><\/h5>\n<div class=\"ex\">\n            <a href=\"https:\/\/java2blog.com\/find-common-elements-in-two-lists-python\/\" target=\"_blank\" rel=\"noopener\">Read more \u2192<\/a>\n        <\/div>\n<\/div>\n<div class=\"rm-item\">\n<h5><a href=\"https:\/\/java2blog.com\/remove-from-list-python\/\" target=\"_blank\" rel=\"noopener\">Remove from Lists in Python<\/a><\/h5>\n<div class=\"ex\">\n            <a href=\"https:\/\/java2blog.com\/remove-from-list-python\/\" target=\"_blank\" rel=\"noopener\">Read more \u2192<\/a>\n        <\/div>\n<\/p><\/div>\n<\/div>\n<\/section>\n","protected":false},"excerpt":{"rendered":"<p>A list is one of Python&#8217;s fundamental in-built data types and clusters several items in a single variable. In this article, we will demonstrate the different ways available to retrieve the list intersection in Python. What is the list intersection in Python? The intersection of two lists returns the elements that are present in both [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":18313,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[145,146],"tags":[],"_links":{"self":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/16186"}],"collection":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/comments?post=16186"}],"version-history":[{"count":0,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/16186\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media\/18313"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=16186"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=16186"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=16186"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}