Contents
Python – Check if List Contains all Elements of Another List
To check if a list contains all elements of other list, use all() function with iterable generated from the list comprehension where each elements represent a boolean value if the element in the other list is present in the source list.
all() built-in Python function returns true if all the elements of this iterable are True.
As an alternate approach, we can also use nested for loop.
Example 1: Check if List 1 Contains all Elements of List 2 using all()
In this example, we will take two lists: list_1 and list_2. We will initialize these lists with some elements. Then we shall write list comprehension and pass this as argument to all() method.
Python Program
list_1 = ['a', 'b', 'c', 'd', 'e']
list_2 = ['a', 'c', 'e']
if all(x in list_1 for x in list_2) :
print("List 1 contains all elements of list 2.")
else:
print("List 1 does not contain all elements of list 2.")
Run Output
List 1 contains all elements of list 2.
Example 2: Check if List 1 Contains all Elements of List 2 using Nested For
In this example, we will use nested for loop to check if a list (list_1) contains all elements of another list (list_2).
Python Program
list_1 = ['a', 'b', 'c', 'd', 'e']
list_2 = ['a', 'c', 'e']
isPresent = True
for x in list_2:
x_present = False
for y in list_1:
if x == y:
x_present = True
break
if not x_present:
isPresent = False
break
if isPresent :
print("List 1 contains all elements of list 2.")
else:
print("List 1 does not contain all elements of list 2.")
Run Output
List 1 contains all elements of list 2.
Summary
In this tutorial of Python Examples, we learned how to check if a list contains all elements of another list.
Related Tutorials
- How to Reverse Python List?
- Python List without Last Element
- Python Program to Find Unique Items of a List
- Python – List of Strings
- How to Sort Python List?
- Python Program to Find Smallest Number in List
- Python List with First N Elements
- How to Access List Items in Python?
- How to Insert Item at Specific Index in Python List?
- Python – Check if Element is in List