Python check if the list contains elements of another list | Example code

There are 2 ways to understand check if the list contains elements of another list. First, use all() functions to check if a Python list contains all the elements of another list.

And second, use any() function to check if the list contains any elements of another one.

Check if a list contains elements of another list example

Simple Program to check the list contains elements of another list.

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("The list1 contains all elements of the list2")
else:
    print("No, List1 doesn't have all elements of the List2.")

Output:

Python check if the list contains elements of another list

any() method

Using any() & a List comprehension:

List1 = ['python', 'JS', 'c#', 'go', 'c', 'c++']
List2 = ['c#', 'Java', 'python']

check = any(item in List1 for item in List2)

if check:
    print("The list1 contains some elements of the list2")
else:
    print("No, List1 doesn't have any elements of the List2.")

Output: The list1 contains some elements of the list2

Another method using loop

This basic custom search approach where tests if the first list contains the second one using a while loop.

While iterating the lists if get an overlapping element, then the function returns true. The search continues until there is no element to match and returns false.

def list_contains(List1, List2):
    check = False

    # Iterate in the 1st list
    for m in List1:

        # Iterate in the 2nd list
        for n in List2:

            # if there is a match
            if m == n:
                check = True
                return check

    return check


List1 = ['a', 'e', 'i', 'o', 'u']
List2 = ['x', 'y', 'z', 'l', 'm']
print(list_contains(List1, List2))

Output: False

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.