Python checks if two lists have common elements | Example code

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:

Python checks if two lists have common elements

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

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.