2
votes
list1 = [[['a','b'],['c','d']],[['f','g'],['h','i']],[['j','k','l'], ['a','b']]]
list2 = [['a','b'],['c','d'],['f','g'],['h','i']]

So in list1, there are 3 lists. I want to check that lists of lists in list1 are subset of list 2. But all lists within list of lists have to be in list2 for it to get True/Correct. It's true if everything is in list2, or false if not per list of list.

[['a','b'],['c','d']]
[['f','g'],['h','i']]
[['j','k','l'], ['a','b']]

So condition is as below

These are from list1, and we're checking against list2

Both [a, b] and [c, d] should be in list 2 -> Both are in list 2, so Return True
Both [f, g] and [h, i] should be in list 1 -> Both are in list 2, so return true
Both [j, k, l] and [a, b] should be in list 1 -> f, k, l is not in list 2, so return False even though a, b are in list 2

Here is my desired output for above results

[True, True, False] 

or

val1 = True
val2 = True
val3 = False

code

def xlist(list1, list2):
    if all(letter in list1 for letter in list2):
        print('True')

print xlist(list1, list2)

final = []
"""I am checking i in list1. In actual, I should be checking all lists within the list of list1."""
    for i in list1:
        print(xlist(list1, list2))
        final.append(xlist(list1, list2))
        print(final)
1
Although obvious, you didn't put what actually goes wrong. If you get an error you should attach it. If your output is wrong, you should show us the actual one against the expected one (which you actually did so just the actual one is missing) - Tomerikoo

1 Answers

4
votes

Your problem is that you don't return any value from your xlist function (print is not the same thing as return). Change it to:

def xlist(list1, list2):
    return all(letter in list1 for letter in list2)

Then:

final = []
for i in list1:
    final.append(xlist(list2, i))
print(final)

The result is:

[True, True, False]

As an alternative, shorter method, you can use the all function with a nested list comprehension:

>>> list1 = [[['a','b'],['c','d']],[['f','g'],['h','i']],[['j','k','l'], ['a','b']]]
>>> list2 = [['a','b'],['c','d'],['f','g'],['h','i']]
>>> [all(item in list2 for item in sublist) for sublist in list1]
[True, True, False]