python

Python Check If a List Contains Elements of Another List

In this tutorial, we are going to see how to check if a Python list contains all the elements of another list and display the result using the print() function.

Suppose we have two lists, list1 and list2, like below.

list1 = ['Hi' ,  'welcome', 'to', 'stackhowto']
list2 = ['to', 'stackhowto']

 

 

Check If a List Contains Elements of Another List Using all() Method
check = all(item in list1 for item in list2)

if check:
    print ("List1 contains all the elements of list2")
else :
    print ("List1 does not contain all the elements of list2")

Output:

List1 contains all the elements of list2

The all() function returns True if all the elements of an Iteration are true, otherwise it returns False.
 

Check If a List Contains Elements of Another List Using any() Method
check =  any(item in list1 for item in list2)

if check:
    print ("List1 contains all the elements of list2")
else :
    print ("List1 does not contain all the elements of list2")

Output:

List1 contains all the elements of list2

Python’s any() function is one of the built-in functions. It takes the iterable as an argument and returns “True” if any of the elements is “True”. If the iterable is empty, it returns “False”.
 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *