Miray
Miray

Reputation: 57

Python Check if a 2-dimensional list contains numbers of another list

I want to know if a list contains numbers from a list of a list, but nothing I tried worked as I wanted. For example if a list of a list in list2 = [[1,2,3],[4,5,6]] is in list1 = [4, 5, 6, 7] it should print out True, because the numbers of list1 are a whole list from list2. So because list1 contains the numbers 4, 5, 6 the output should be True.

Here is what I tried

for i in range(len(list2)):
    if list1 in list2[i]:
        print('True')
    else:
        print('False')

It prints out False two times (but I need it to print out True) and I get why

[1, 2, 3] in [1, 2, 3, 4]
>>> False

Is there a way to avoid this? Or should I just use strings since it works with them just fine?

Upvotes: 3

Views: 158

Answers (1)

Olivier Melançon
Olivier Melançon

Reputation: 22294

Finding if a collection of items is a subset of another is more efficiently handled by a set than a list. Casting your list to a set allow quick lookup with the set.issuperset method.

list_of_lists = [[1,2,3],[4,5,6]]
list1 = [4, 5, 6, 7]

list1_as_set = set(list1)

result = any(list1_as_set.issuperset(l) for l in list_of_lists) # True

The above code using any is equivalent to this solution using a for-loop.

for l in list_of_lists:
    if list1_as_set.issuperset(l):
        result = True
        break
else:
    result = False

Upvotes: 2

Related Questions