
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python - Check if a list is contained in another list
Given two different python lists we need to find if the first list is a part of the second list.
With map and join
We can first apply the map function to get the elements of the list and then apply the join function to cerate a comma separated list of values. Next we use the in operator to find out if the first list is part of the second list.
Example
listA = ['x', 'y', 't'] listB = ['t', 'z','a','x', 'y', 't'] print("Given listA elemnts: ") print(', '.join(map(str, listA))) print("Given listB elemnts:") print(', '.join(map(str, listB))) res = ', '.join(map(str, listA)) in ', '.join(map(str, listB)) if res: print("List A is part of list B") else: print("List A is not a part of list B")
Output
Running the above code gives us the following result −
Given listA elemnts: x, y, t Given listB elemnts: t, z, a, x, y, t List A is part of list B
With range and len
We can design a for loop to check the presence of elements form one list in another using the range function and the len function.
Example
listA = ['x', 'y', 't'] listB = ['t', 'z','a','x', 'y', 't'] print("Given listA elemnts: \n",listA) print("Given listB elemnts:\n",listB) n = len(listA) res = any(listA == listB[i:i + n] for i in range(len(listB) - n + 1)) if res: print("List A is part of list B") else: print("List A is not a part of list B")
Output
Running the above code gives us the following result −
Given listA elemnts: ['x', 'y', 't'] Given listB elemnts: ['t', 'z', 'a', 'x', 'y', 't'] List A is part of list B
- Related Articles
- How to check if a substring is contained in another string in Python
- Check if list is strictly increasing in Python
- FabricJS – Check if a Polygon Object is Fully Contained within Another Object?
- How to check if a list is empty in Python?
- Python - Insert list in another list
- Check if a list exists in given list of lists in Python
- Check if list is sorted or not in Python
- How to check if one list against another in Excel?
- Check if a linked list is Circular Linked List in C++
- Check if a number in a list is perfect square using Python
- Python - Check if a List contain particular digits
- Update a list of tuples using another list in Python
- Check if one list is subset of other in Python
- Python – Check if any list element is present in Tuple
- What is best way to check if a list is empty in Python?

Advertisements