How to find common elements in two lists Python using for loop

2021-11-02 19:10:11 / Python

list1 = [1,2,3,4,5,6] list2 = [3, 5, 7, 9] list(set(list1).intersection(list2))


len([x for x in list1 if x in list2])

x = {2, 3, 5, 6} y = {1, 2, 3, 4} z = x.intersection(y)

list1 = ['little','blue','widget'] list2 = ['there','is','a','little','blue','cup','on','the','table'] list3 = set(list1)&set(list2) list4 = sorted(list3, key = lambda k : list1.index(k))

>>> list1 = [1,2,3,4,5,6] >>> list2 = [3, 5, 7, 9] >>> list(set(list1).intersection(list2)) [3, 5]

# using numpy import numpy as np a = np.array([1,2,3,2,3,4,3,4,5,6]) b = np.array([7,2,10,2,7,4,9,4,9,8]) # using intersect1d print(np.intersect1d(a,b)) # output # [2 4]

Are there any code examples left?

This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Sign up to unlock all of IQCode features:

  • Master useful skills
  • Improve learning outcomes
  • Share your knowledge
How to find common elements in two lists Python using for loop

Basic way to checks if two lists have common elements is using traversal of lists in Python. You can checks single match or all element match between 2 lists.

Python checks if two lists have common elements

Simple example code where given two lists a, b. Check if two lists have at least one element common in them or all elements are same.

Check if two lists have at-least one element common

Using for loop

def common_ele(list1, list2): res = False # traverse in the 1st list for x in list1: # traverse in the 2nd list for y in list2: # if one common if x == y: res = True return res return res a = [1, 2, 3, 4, 5] b = [6, 7, 8, 9, 5] print(common_ele(a, b))

Using Set Intersection

set.intersection will find any common elements:

def common_ele(list1, list2): a_set = set(a) b_set = set(b) if len(a_set.intersection(b_set)) > 0: return True return False a = [1, 2, 3, 4, 5] b = [6, 7, 8, 9, 5] print(common_ele(a, b))

Output: True

Check if Python List Contains All Elements of Another List

Use the all() method.

List1 = ['python', 'JS', 'c#', 'go', 'c', 'c++'] List2 = ['c#', 'Java', 'python'] check = all(item in List1 for item in List2) if check: print("Both list same") else: print("No, lists are not same.")

Output:

How to find common elements in two lists Python using for loop

Do comment if you have any doubts and suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

How to find common elements in two lists Python using for loop

Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.

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:

Preparation

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.

  • How to install NumPy on PyCharm

Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import numpy as np

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.

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

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.

Good Luck & Happy Coding!

How to find common elements in two lists Python using for loop

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