As the title mentions,is there any builtins to do this job?I looked for that in dir(list)
but got no usable one.Thanks.
Assuming that you want to see if all elements of sublist
are also elements of superlist
:
all(x in superlist for x in sublist)
Depends on what you mean by "contained". Maybe this:
if set(a) <= set(b):
print "a is in b"
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...)
You might want to use a set
if set(a).issubset(b):
print('a is contained in b')