List intersection in python

List intersection in Python

A list is one of Python’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 lists. There are several methods to find these elements.

Ways to find the list intersection in Python

Using the for loop to achieve list intersection in Python

Instead of using any built-in functions available for this purpose, we can always create a simple user-defined function using the for loop.

For example,

The above code provides the following output:

[1, 5]
Explanation
  • We first define two lists named X and Y in the above code.
  • We create a user-defined function that uses the for loop to traverse the list and find the common elements.
  • We store these elements in a new list intsec and display them.

List comprehension can simplify the code and make the syntax compact in this case.

For example,

The above code provides the following output:

[1, 5]

This method increases the program’s efficiency, dropping its complexity to O(n).

Using the set() function to find list intersection in Python

We first convert the given lists into sets individually using the set() method. Then we apply the intersection on the two sets using the intersection & operator, which returns the intersection between the two sets.

See the code below.

The above code provides the following output:

[1, 5]
Explanation
  • The two lists X and Y are defined.
  • Both the lists are converted into sets using the set() method.
  • We carry out the intersection operation using the & operator.
  • The result is stored in Z and is displayed.

Using the intersection() function to find list intersection in Python

Sets have an in-built method, intersection(), which can quickly get the common items between sets. The intersection() function will return the common values from both sets in a freshly generated set.

The lists need to be explicitly converted into sets first, as done in the previous method to use this function.

See the code below.

The above code provides the following output:

[1, 5]

Using the filter() and lambda functions to find list intersection in Python

Python’s filter() 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.

Here, we will also take help from the lambda function. A lambda function is a single-expression, one-line function that can take any number of arguments.

We use both these functions in the following example.

The above code provides the following output:

[1, 5]
Explanation
  • We create the two lists.
  • The filter() 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.
  • If this is True, then we store the element in the list Z.

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.

Using the Counter class to find list intersection in Python

The Counter is a class from the collections module that keeps track of all the items’ frequency of occurrence in a given iterable. We can use it to return the list intersection of two lists.

For example,

The above code provides the following output:

[1, 5]
Explanation
  • We apply the Counter() constructor to both lists.
  • We perform the intersection operation on both X and Y using the & operator.
  • We store the elements of this class in Z using the elements() function.
  • Finally, we display the common elements.

Using the numpy.intersect1d() function to find list intersection in Python

The numpy.intersect1d function returns an array containing the intersection of two given arrays. We can convert this final result to a list using the list() function.

For example,

Output:

[1, 5]

That’s all about list intersection in Python.


import_contacts

You may also like:

Related Posts

  • 07 January

    How to compare lists in Python

    Table of ContentsPython compare listsHow to compare lists in PythonUsing the sort() function and == operatorUsing the map() and reduce() functionsUsing the set() function and == operatorUsing the for loopUsing the set() function and - operatorUsing the collections.Counter() class and == operatorUsing the zip(), sum(), and len() functionsUsing the cmp() functionConclusion In this post, we […]

  • Python List of dictionaries
    09 December

    List of Dictionaries in Python

    Table of ContentsHow to Create a List of Dictionaries in Python?How to Access Elements of a List of Dictionaries?Search in a List of Dictionaries in PythonUpdate Values in a List of Dictionaries in PythonHow to Sort List of Dictionaries in Python?Conclusion We use both lists and dictionaries in our python programs. Lists are used to […]

  • Python sort list of lists
    17 November

    Sort List of Lists in Python

    Table of ContentsSort List of Lists Using the sort() Method in PythonUsing the itemgetter() methodUsing Lambda FunctionsSort List of Lists Using the sorted() Function in PythonSort lists of lists on the basis of the length of the inner listsConclusion Several times we use 2-D lists or lists of lists in our programs to represent a […]

  • Remove nan from list in Python
    16 November

    Remove nan From List In Python?

    Table of ContentsWhat is nan in python?How to remove nan from list in python?Remove nan from list using the str() functionRemove nan from list using math.isnan() functionRemove nan from list using numPy.isnan() functionRemove nan from list using pandas.isnull() functionConclusion In python, nan is a special value used to represent missing values. In this article, we […]

  • Initialize list with zeros in Python
    25 October

    Four Ways To Initialize List With Zeros In Python

    Table of ContentsWhy Initialize List with Zeros in Python?How Can We Initialize List With Zeros In Python?Initialize List With Zeros Using * Operator In PythonInitialize List With Zeros Using  itertools.repeat() FunctionInitialize List With Zeros Using  Generator Comprehension In PythonInitialize List With Zeros Using  List Comprehension In PythonConclusion Lists in Python are one of the most […]

  • 06 October

    How to find index of all occurrences in list in Python

    Table of ContentsThe easiest method – Using list count() methodThe Basic Method – Using for loopsThe shortest method – Using the enumerate() functionThe fastest method – Using a numpy arrayUsing itertools moduleUsing more-itertools LibraryUsing index() function List is a data type in Python. It is used to store multiple values in one variable. If you […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.