Skip to content

Python checks if two lists have common elements | Example code

  • by

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

Or by converting the lists to sets and using the intersection operation, you can easily find the common elements between them.

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 the 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:

Python checks if two lists have common elements

Comment if you have any doubts or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.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.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading