Example of how to check if all elements of a list are nested in another list in python:
Table of contents
Check if a list is a subset of another list
Let's consider two lists:
Considérons deux listes l1 et l2 quelconques et on veut vérifier que l1 est imbriquée ("nested" en anglais) dans l2 (c.a.d que tous les éléments de l1 sont également dans l2). Pour cela prenons, tout d'abord comme exemple:
l1 = [1,2,3,4]
and
l2 = [9,8,7,6,5,4,3,2,1]
to check if all elements of the list l1 are also in l2, a solution is to use issubset:
set(l1).issubset(set(l2))
returns
True
Note: to check if l2 is a superset of l1, a solution is to use issuperset:
l1 = [1,2,3,4]
l2 = [9,8,7,6,5,4,3,2,1]
set(l2).issuperset(set(l1))
returns
True
Another example: if a new elements is added to l1 which is not in l2:
l1 = [1,2,3,4]
l1.append(21)
then
set(l1).issubset(set(l2))
returns
False
References
- set | python doc
- How to check if all of the following items are in a list? | stackoverflow
- set | rgruet.free.fr