Check if one list is a subset of another in Python

| | | | | | | | | | | | | | | | | | | | | | |
A list is a subset of another list if all elements of the former are also elements of the latter. For example, [1, 2] is a subset of [1, 2, 3], but [1,4] is not. USE set.issubset() TO CHECK IF A LIST IS A SUBSET OF ANOTHER LIST Use set(list) to convert the lists to sets. Call set1.issubset(set2) to return a Boolean indicating whether set1 is a subset of set2.
print(list1)
OUTPUT
[1, 2]
print(list2)
OUTPUT
[1, 2, 3]
set1 = set(list1)
Convert lists to sets

set2 = set(list2)

is_subset = set1.issubset(set2)
Check if set1 is found in set2

print(is_subset)
OUTPUT
True

Check if one list is a subset of another in Python

Python check if list is subset of another

Sometimes we encounter the problem of checking if one list is just an extension of the list i.e just a superset of one list. This kind of problems are quite popular in competitive programming. Having shorthands for it helps the cause. Lets discuss various ways to achieve this particular task.

Check if one list is a subset of another Using all()

all() is used to check all the elements of a container in just one line. Checks for all the elements of one list for existence in other list.
# Python3 code to demonstrate
# to check if list is subset of other
# using all()

# initializing list
test_list = [9, 4, 5, 8, 10]
sub_list = [10, 5, 4]

# printing original lists
print ("Original list : " + str(test_list))
print ("Original sub list : " + str(sub_list))

# using all() to
# check subset of list
flag = 0
if(all(x in test_list for x in sub_list)):
	flag = 1
	
# printing result
if (flag) :
	print ("Yes, list is subset of other.")
else :
	print ("No, list is not subset of other.")

Output:

Original list : [9, 4, 5, 8, 10] Original sub list : [10, 5, 4] Yes, list is subset of other.

Check if one list is a subset of another Using set.issubset()

The most commonly used and recommended way to search for a sublist. This function is tailor-made to accomplish the particular task of checking whether one list is a subset of another.
# Python3 code to demonstrate
# to check if list is subset of other
# using issubset()
 
# initializing list
test_list = [9, 4, 5, 8, 10]
sub_list = [10, 5]
 
# printing original lists
print ("Original list : " + str(test_list))
print ("Original sub list : " + str(sub_list))
 
# using issubset() to
# check subset of list
flag = 0
if(set(sub_list).issubset(set(test_list))):
    flag = 1
     
# printing result
if (flag) :
    print ("Yes, list is subset of other.")
else :
    print ("No, list is not subset of other.")

Output:

Original list : [9, 4, 5, 8, 10]
Original sub list : [10, 5]
Yes, list is subset of other.

How to check if one list is a subset of another in Python

Check if one list is a subset of another Using iteration and counter

Use the number of items in both lists to verify that the second list is a subset of the first list.
# Python3 code to demonstrate
# to check if list is subset of other
 
#Importing
from collections import Counter
 
def checkInFirst(a, b):
     #getting count
    count_a = Counter(a)
    count_b = Counter(b)
 
    #checking if element exists in second list
    for key in count_b:
        if key not in  count_a:
            return False
        if count_b[key] > count_b[key]:
            return False
    return True
 
# initializing list
a = [1, 2,4,5]
b = [1, 2,3]
 
#Calling function
res = checkInFirst(a, b)
 
#Printing list
print ("Original list : " + str(a))
print ("Original sub list : " + str(b))
 
if res==True :
    print ("Yes, list is subset of other.")
else :
    print ("No, list is not subset of other.")
     
#Added by Paras Jain(everythingispossible)

Output:

Original list : [1, 2, 4, 5]
Original sub list : [1, 2, 3]
No, list is not subset of other.

Check if one list is a subset of another Using set.intersection()

Another method that deals with sets is to see if the intersection of both lists is the sublist that we are checking. This confirms that one list is a subset of the other.
# Python3 code to demonstrate
# to check if list is subset of other
# using intersection()
 
# initializing list
test_list = [9, 4, 5, 8, 10]
sub_list = [10, 5]
 
# printing original lists
print ("Original list : " + str(test_list))
print ("Original sub list : " + str(sub_list))
 
# using intersection() to
# check subset of list
flag = 0
if((set(sub_list) & set(test_list))== set(sub_list)):
    flag = 1
     
# printing result
if (flag) :
    print ("Yes, list is subset of other.")
else :
    print ("No, list is not subset of other.")

Output:

Original list : [9, 4, 5, 8, 10]
Original sub list : [10, 5]
Yes, list is subset of other.

Determine if one list is a subset of another in Python

How to check if one list is a subset of another Python?

Python Set issubset() method returns True if all elements of a set are present in another set (passed as an argument). If not, it returns False. Set A is said to be the subset of set B if all elements of A are in B.

How can I verify if one list is a subset of another?

StackOverflow question

I need to verify if a list is a subset of another - a boolean return is all I seek. Is testing equality on the smaller list after an intersection the fastest way to do this? Performance is of utmost importance given the number of datasets that need to be compared. Adding further facts based on discussions: Will either of the lists be the same for many tests? It does as one of them is a static lookup table. Does it need to be a list? It does not - the static lookup table can be anything that performs best. The dynamic one is a dict from which we extract the keys to perform a static lookup on. What would be the optimal solution given the scenario?

Answer:

Use set.issubset Example:
a = {1,2}
b = {1,2,3}
a.issubset(b) # True
a = {1,2,4}
b = {1,2,3}
a.issubset(b) # False

The performant function Python provides for this is set.issubset. It does have a few restrictions that make it unclear if it’s the answer to your question, however. A list may contain items multiple times and has a specific order. A set does not. Additionally, sets only work on hashable objects. Are you asking about subset or subsequence (which means you’ll want a string search algorithm)? Will either of the lists be the same for many tests? What are the datatypes contained in the list? And for that matter, does it need to be a list? Your other post intersect a dict and list made the types clearer and did get a recommendation to use dictionary key views for their set-like functionality. In that case it was known to work because dictionary keys behave like a set (so much so that before we had sets in Python we used dictionaries). One wonders how the issue got less specific in three hours.

Shop

Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best laptop for development

$499+
Gifts for programmers

Best laptop for Cricut Maker

$299+
Gifts for programmers

Best laptop for hacking

$890
Gifts for programmers

Best laptop for Machine Learning

$699+
Gifts for programmers

Raspberry Pi robot kit

$150

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically