Count common elements in two lists Python

In this article, you’ll learn how to locate and return the common elements of two (2) lists in Python.

To make it more fun, we have the following running scenario:

Bondi Brokers offers two (2) Marketable Bonds: 3-years and 5-years. Each yields different amounts. To determine which Bond best suits their customer’s needs, they need to find the commonality between them. They have requested your assistance in this regard.

💬 Question: How would we write Python code to locate and return the commonalities?

We can accomplish this task by one of the following options:

Method 1: Use intersection()

In this example, the intersection() method compares two (2) sets, locates the common elements, and returns them as a new set while preserving the order.

bond_3_yr = {2.56, 2.59, 2.68, 2.43, 2.47, 2.11} bond_5_yr = {2.78, 2.59, 2.68, 2.58, 2.62, 2.65} result = bond_3_yr.intersection(bond_5_yr) print(result)

This code calls the intersection() method and passes bond_5_yr as an argument. The common elements are located and saved to result. The contents of result are output to the terminal.

Python set.intersection() & "&" & Explanations & Examples & Runtime

Output

Method 2: Use intersection1d()

The np.intersect1d() accepts two lists, compares and locates the common elements, and returns a sorted list.

import numpy as np bond_3_yr = [2.56, 2.59, 2.68, 2.43, 2.47, 2.11] bond_5_yr = [2.78, 2.59, 2.68, 2.58, 2.62, 2.65] result = np.intersect1d(bond_3_yr, bond_5_yr) print(result)

This code calls the np.intersect1d() method and passes bond_3_yr and bond_5_yr as arguments. The common elements are located, sorted, and saved to result. The contents of result are output to the terminal.

Output

Before our code executes successfully, one (1) new library will require installation.

  • The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.

To install this library, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installation was successful, a message displays in the terminal indicating the same.

Feel free to view the PyCharm installation guide for the required library.

🌍 Recommended Tutorial: How to install NumPy on PyCharm

Method 3: Use List Comprehension

Another method to find comment elements is by using List Comprehension. This locates and returns a list of common elements while preserving the order.

bond_3_yr = [2.56, 2.59, 2.68, 2.43, 2.47, 2.11] bond_5_yr = [2.78, 2.59, 2.68, 2.58, 2.62, 2.65] result = [element for element in bond_3_yr if element in bond_5_yr] print(result)

This code loops through each element and saves the common elements found to result. The contents of result are output to the terminal.

A Simple Introduction to List Comprehension in Python

Output

Method 4: Use List Comprehension with Set

A more efficient variant of using list comprehension to find the common elements of two lists l1 and l2 is to convert one list to a set so that the second membership “in” operator in the expression [x for x in l1 if x in set(l2)] has only constant instead of linear runtime complexity.

This approach reduces runtime complexity from O(n²) without the set conversion to O(n) with the set conversion:

  • [x for x in l1 if x in l2] – > quadratic runtime complexity O(n²)
  • [x for x in l1 if x in set(l2)] – > linear runtime complexity O(n)

Here’s the obligatory code example solving the same problem more efficiently than Method 3 without the set() conversion.

bond_3_yr = [2.56, 2.59, 2.68, 2.43, 2.47, 2.11] bond_5_yr = [2.78, 2.59, 2.68, 2.58, 2.62, 2.65] result = [element for element in bond_3_yr if element in set(bond_5_yr)] print(result) # [2.59, 2.68]

Method 5: Use set()

The most compact method is to use set(). This compares the sets and returns the common elements. Unfortunately, the order is not preserved.

bond_3_yr = [2.56, 2.59, 2.68, 2.43, 2.47, 2.11] bond_5_yr = [2.78, 2.59, 2.68, 2.58, 2.62, 2.65] result = set(bond_3_yr) & set(bond_5_yr) print(result)

This code, as indicated above, takes two (2) Lists, compares and saves the common elements to result. The contents of result are output to the terminal.

13 Set Operations Every Python Master Knows

Output

Summary

These four (4) methods to find the common elements should give you enough information to select the best one for your coding requirements.

🌍 Recommended: If you’re interested in similar problems, have a look at those:

Good Luck & Happy Coding!

At university, I found my love of writing and coding. Both of which I was able to use in my career.

During the past 15 years, I have held a number of positions such as:

In-house Corporate Technical Writer for various software programs such as Navision and Microsoft CRM Corporate Trainer (staff of 30+) Programming Instructor Implementation Specialist for Navision and Microsoft CRM

Senior PHP Coder

This post will discuss how to find common elements from two lists in Python.

1. Using intersection() function

A simple and fairly efficient solution is to convert the first list into a set and then call the intersection() function. It returns a new set with elements common to the set with another iterable.

if __name__ == '__main__':

    common = set(first).intersection(second)

Download  Run Code

2. Using bitwise comparison

You can also use the operator-based counterpart of intersection(), which happens to be bitwise, and (&) operator. But this requires both arguments to be set, as shown below:

if __name__ == '__main__':

    common = set(first) & set(second)

Download  Run Code

3. Using List Comprehension

Finally, you can find common elements from two lists using list comprehensions by searching each element of the first list in the second list. The time complexity of this solution is quadratic, and this is definitely not a recommended solution for large lists.

if __name__ == '__main__':

    common = [x for x in first if x in second]

Download  Run Code

That’s all about finding the common elements from two lists in Python.


Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding 🙂


Postingan terbaru

LIHAT SEMUA