Search code examples
pythonlistcomparison

How to check if a nested list is a subset of another nested list


I have 2 lists as list<list<list>> lists where I want to check if one of them is a subset of the other.

list_1 = [
           [
             [1,2],[2,3]
           ],
           [
             [3,4],[5,6]
           ]
         ]
list_2 = [
           [
             [3,4], [5, 6]
           ]
         ]

So expected output is that as list2 has [[[3,4]]] which is a part of list_1 so it should be a subset.

list_1 has 2 elements and its second element matches the first element in list_2 so list_2 is a subset of list_1.

The comparison is not at the element level but at list level.

I tried set(list_2) < set(list_1) but results in unhashable type: list. How can I achieve the above comparison then?


Solution

  • You can iterate over list_2 and check whether its elements are contained in list_1:

    list_1 = [[[1, 2], [2, 3]], [[3, 4], [5, 6]]]
    list_2 = [[[3, 4], [5, 6]]]
    
    all(x in list_1 for x in list_2)  # Option 1.
    all(map(list_1.__contains__, list_2))  # Option 2.
    

    The second version works for lists (and other types) but a in b is more general since it falls back on b.__iter__ if b.__contains__ is not defined.