Young
Young

Reputation: 8356

How to check if a list is contained inside another list without a loop?

Is there any builtins to check if a list is contained inside another list without doing any loop?

I looked for that in dir(list) but found nothing useful.

Upvotes: 30

Views: 33962

Answers (5)

Luka H
Luka H

Reputation: 69

If you want to validate that all the items from the list1 are on list2 you can do the following list comprehension:

all(elem in list1 for elem in list2)

You can also replace list1 and list2 directly with the code that will return that list

all([snack in ["banana", "apple", "lemon", "chocolate", "chips"] for snack in ["chips","chocolate"])

That any + list comprehension can be translated into this for a better understanding of the code

return_value = False
for snack in snacks:
   if snack in groceries:
     return_value = True
   else:
     return_value = False

Upvotes: -1

Etaoin
Etaoin

Reputation: 8724

Assuming that you want to see if all elements of sublist are also elements of superlist:

all(x in superlist for x in sublist)

Upvotes: 23

nosklo
nosklo

Reputation: 222842

Depends on what you mean by "contained". Maybe this:

if set(a) <= set(b):
    print("a is in b")

Upvotes: 58

jesteras
jesteras

Reputation: 151

You might want to use a set

if set(a).issubset(b):
    print('a is contained in b')

Upvotes: 14

Adrien Plisson
Adrien Plisson

Reputation: 23293

the solution depends on what values you expect from your lists.

if there is the possiblity of a repetition of a value, and you need to check that there is enough values in the tested container, then here is a time-inefficient solution:

def contained(candidate, container):
    temp = container[:]
    try:
        for v in candidate:
            temp.remove(v)
        return True
    except ValueError:
        return False

test this function with:

>>> a = [1,1,2,3]
>>> b = [1,2,3,4,5]
>>> contained(a,b)
False    
>>> a = [1,2,3]
>>> contained(a,b)
True
>>> a = [1,1,2,4,4]
>>> b = [1,1,2,2,2,3,4,4,5]
>>> contained(a,b)
True

of course this solution can be greatly improved: list.remove() is potentially time consuming and can be avoided using clever sorting and indexing. but i don't see how to avoid a loop here...

(anyway, any other solution will be implemented using sets or list-comprehensions, which are using loops internally...)

Upvotes: 6

Related Questions