sfortney
sfortney

Reputation: 2123

Checking if all elements of a List of Lists are in another List of Lists Python

My question is, how do you check if all of the elements of a list of lists are in another list of lists? Or maybe better phrased, how do you check if one list of lists is a subset of another list of lists? The answer posted below only works if you have a list of, say, strings but the answer does not work for my situation.

How to check if all items in a list are there in another list?

Something I have tried is something like this:

if all(item in list1 for item in list2): 

which does not work.

Upvotes: 1

Views: 2455

Answers (2)

Akavall
Akavall

Reputation: 86198

Convert your sublists to tuples, for example:

In [2]: a = [[2,3],[5,6],[8,9]]

In [3]: b = [[2,3],[5,6],[8,9], [10,11]]

In [4]: set(tuple(x) for x in a).issubset(tuple(x) for x in b)
Out[4]: True

Upvotes: 5

ljetibo
ljetibo

Reputation: 3094

This is really really easy if you just even tried to see what that piece of code gave you...

>>> l1 = [1,2]
>>> l2 = [1,2,3,4,5]
>>> all(l1)
True
>>> [item in l1 for item in l2]
[True, True, False, False, False]
>>> help(all)
Help on built-in function all in module builtins:

all(...)
    all(iterable) -> bool

    Return True if bool(x) is True for all values x in the iterable.
    If the iterable is empty, return True.

Anyhow you need to turn them into sets and compute the issubset method

>>> s1 = set(l1)
>>> s2 = set(l2)
>>> s1.issubset(s2)
True

Edit yes, as others have noted this only works if all the elements of the list are unique and you're not looking for a set math but for an exact match since sets are by default a collection of unique objects.

Upvotes: 1

Related Questions