How do I check if a list contains all the elements of another list in Python? It's not working
Question:
list1 = ['Gryffindor', 'Ravenclaw', 'Hufflepuff', 'Slytherin']
list2 = ['Gryffindor', 'Ravenclaw']
checkif = item in List2 for item in List1
if check is True:
print("The list {} contains all elements of the list {}".format(List1, List2))
Why is this damn thing not working? Also is checkif = item in list2 for item in list1
a list comprehension or what?
Someone please correct my code, thanks.
Answers:
You can use sets here and specifically check the relationship whether one of your sets is a subset of the other:
set(list2).issubset(list1) # True
To use this the first object must be a set hence set(list2)
but the second can be any iterable. One caveat here is that since we’re comparing sets, it will only check for unique elements, i.e. it will not care about repeated values.
I think you want all
:
list1 = ['Gryffindor', 'Ravenclaw', 'Hufflepuff', 'Slytherin']
list2 = ['Gryffindor', 'Ravenclaw']
checkif = all(item in list1 for item in list2)
Also, you need to swap list1
and list1
to get the result you describe in the print
line.
list1 = ['Gryffindor', 'Ravenclaw', 'Hufflepuff', 'Slytherin']
list2 = ['Gryffindor', 'Ravenclaw']
checkif = item in List2 for item in List1
if check is True:
print("The list {} contains all elements of the list {}".format(List1, List2))
Why is this damn thing not working? Also is checkif = item in list2 for item in list1
a list comprehension or what?
Someone please correct my code, thanks.
You can use sets here and specifically check the relationship whether one of your sets is a subset of the other:
set(list2).issubset(list1) # True
To use this the first object must be a set hence set(list2)
but the second can be any iterable. One caveat here is that since we’re comparing sets, it will only check for unique elements, i.e. it will not care about repeated values.
I think you want all
:
list1 = ['Gryffindor', 'Ravenclaw', 'Hufflepuff', 'Slytherin']
list2 = ['Gryffindor', 'Ravenclaw']
checkif = all(item in list1 for item in list2)
Also, you need to swap list1
and list1
to get the result you describe in the print
line.