Python : Check if a List Contains all the Elements of Another List

In Python, the list datatype is that the most versatile, and it are often written as an inventory of comma-separated values (items) enclosed in square brackets.

Given two lists, the task is to check whether the second list has all the elements of first list.

Examples:

Input:

givenlist1 = ['Hello' , 'this', 'is', 'Btech', 'Geeks']
givenlist2 = ['Btech','Geeks']
Output:
givenlist2 has all of the  givenlist1 elements

Input:

givenlist1 = ['Hello' , 'this', 'is', 'Btech', 'Geeks']
givenlist2 = ['Btech','Geeks','pink']
Output:
givenlist2 doesn't have all of the  givenlist1 elements

Determine whether  a list is included inside another list

There are several ways to check if a list is contained in another list some of them are:

Method #1:Using any() function

The function any() returns True if any of the items in an iterable are true; otherwise, False. The any() function returns False if the iterable object is empty.

Convert list2 to Iterable and check if any element in Iterable, i.e. list2, exists in list1.

Below is the implementation:

# given two lists
givenlist1 = ['Hello', 'this', 'is', 'Btech', 'Geeks']
givenlist2 = ['Btech', 'Geeks']
# using any()
if(any(element in givenlist1 for element in givenlist2)):
    print("givenlist2 has all of the  givenlist1 elements")
else:
    print("givenlist2 doesn't have all of the  givenlist1 elements")

Output:

givenlist2 has all of the  givenlist1 elements

Method #2:Using all() function

In a single line, the all() function is used to check all the elements of a container. Checks if all elements from one list are present in another list.

Below is the implementation:

# given two lists
givenlist1 = ['Hello', 'this', 'is', 'Btech', 'Geeks']
givenlist2 = ['Btech', 'Geeks']
# using all()
if(all(element in givenlist1 for element in givenlist2)):
    print("givenlist2 has all of the  givenlist1 elements")
else:
    print("givenlist2 doesn't have all of the  givenlist1 elements")

Output:

givenlist2 has all of the  givenlist1 elements

Method #3:Using set.issubset()

The most commonly used and recommended method for searching for a sublist. This function is specifically designed to determine whether one list is a subset of another.

Below is the implementation:

# given two lists
givenlist1 = ['Hello', 'this', 'is', 'Btech', 'Geeks']
givenlist2 = ['Btech', 'Geeks']
# using set.issubset() function
if(set(givenlist2).issubset(set(givenlist1))):
    print("givenlist2 has all of the  givenlist1 elements")
else:
    print("givenlist2 doesn't have all of the  givenlist1 elements")

Output:

givenlist2 has all of the  givenlist1 elements

Related Programs: