To chek if list A is completely included in list B – all elements of list A are present in list B, we can use the “superset” and “subset” methods of the standard Python “set” class.
Converting lists to sets also allows us not to worry about checking for duplicates if they exist in the compared lists.
subset
The “subset” method acts on a smaller set and checks if it is in a larger set.
1 2 3 4 5 6 7 8 9 |
A = ['a', 'x', 'z'] A1 = ['a', 'x', 'z', 99] B = list('abcdefghijklmnopqrstuvwxyz') # ['a', 'b', ..., 'z'] print(set(A).issubset(set(B))) # True print(set(A1).issubset(set(B))) # False |
superset
The “superset” method, on the contrary, checks the larger set to see if it contains a smaller set.
1 2 3 4 5 6 7 8 9 |
A = ['a', 'x', 'z'] A1 = ['a', 'x', 'z', 99] B = list('abcdefghijklmnopqrstuvwxyz') # ['a', 'b', ..., 'z'] print(set(B).issuperset(set(A))) # True print(set(B).issuperset(set(A1))) # False |
We can also use the “<=” operator to check our lists:
<=
1 2 3 4 5 6 7 8 9 |
A = ['a', 'x', 'z'] A1 = ['a', 'x', 'z', 99] B = list('abcdefghijklmnopqrstuvwxyz') # ['a', 'b', ..., 'z'] print(set(A) <= set(B)) # True print(set(A1) <= set(B)) # False |