Python Check if the List Contains Elements of another List
In Python programming, there can be a case where we have to check whether a list contains elements of Another List or not. In that case, we can follow several approaches for doing so. In this article, we will be discussing several approaches to check whether a list contains elements of another list or not.
Python List Contains Elements of another List
There are several approaches we can follow for Python List Contains Elements Of Another List in Python.
- Using For Loop
- Using all() method
- Using set() & intersection()
Python List Contains Elements Of Another List Check Using For Loop
In this example, below Python code below compares two lists, `list1` and `list2`, and checks if all elements in `list2` are present in `list1`. If any element from `list2` is not found in `list1`, the `check` variable is set to `False`. Finally, if `check` remains `True`, it prints “Elements of list2 exist in list1,” indicating that all elements of `list2` are present in `list1″.
Python
# Declaring both the lists list1 = [ "a" , "b" , "c" , "d" ] list2 = [ "a" , "b" ] check = True for e in list2: if e not in list1: check = False if check = = True : print ( "Elements of list2 exists in list1" ) |
Elements of list2 exists in list1
Python List Contains Elements Of Another List Check Using all() Method
In this example, Python code efficiently checks if all elements in `list2` exist in `list1` using the `all()` function and a generator expression. If the condition holds true for each element in `list2`, it sets the `check` variable to `True`. If `check` remains `True`, the code prints “Elements of list2 exist in list1,” indicating that all elements of `list2` are present in `list1″.
Python
# Declaring both the lists list1 = [ "a" , "b" , "c" , "d" ] list2 = [ "a" , "b" ] check = all (e in list1 for e in list2) if check = = True : print ( "Elements of list2 exists in list1" ) |
Elements of list2 exists in list1
Python List Contains Elements Of Another List Check Using set & intersection() Method
In this example, below Python code efficiently checks if all elements in `list2` exist in `list1` using set intersection. If the lengths match, it prints “Elements of list2 exist in list1,” indicating their presence. This approach offers a concise and effective method for list comparison.
Python
# Declaring both the lists list1 = [ "a" , "b" , "c" , "d" ] list2 = [ "a" , "b" ] intersection_set = set (list1).intersection( set (list2)) if len (intersection_set) = = len (list2): print ( "Elements of list2 exists in list1" ) |
Elements of list2 exists in list1