Active March 29, 2021    /    Viewed 520    /    Comments 0    /    Edit

Example of how to check if all elements of a list are nested in another list in python:

### 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

##### Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!

Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount