tags:

views:

122

answers:

3

How do I check if a list is a subset of a bigger list.

i.e.

a = [1,2,3] is a subset of b = [1,2,3,4,5,6]

Can I do something like

if a all in b
+12  A: 

http://docs.python.org/library/stdtypes.html#set.issubset

set(a).issubset(set(b))
Keep in mind that this will NOT account for repeated elements in the list, e.g. if a = [1, 1, 2, 3] and b = [1, 2, 3, 4], this will still evaluate true.
ezod
@ezod: Right, but if Peter says "set" I think this is correct.
+5  A: 
>>> a = set([1, 2, 3])
>>> b = set([1, 2, 3, 4, 5, 6])
>>> a.issubset(b)
True

or

>>> a = [1, 2, 3]
>>> b = [1, 2, 3, 4, 5, 6]
>>> all(map(lambda x: x in b, a))
True
>>> a = [1, 2, 3, 9]
>>> all(map(lambda x: x in b, a))
False

or (if the number of elements is important)

>>> a = [1, 1, 2, 3]
>>> all(map(lambda x: a.count(x) <= b.count(x), a))
False
jbochi
Still, it has problem with duplicates - assuming that we want to test for e.g. two 1's from 'a' being present in 'b'
Tomasz Zielinski
Indeed... I have edit the answer to provide an alternative solution (not optimized)
jbochi
+2  A: 

mostly like the other answers, but I do prefer the generator syntax here, seems more natural and it's lazily evaluated:

if all(x in b for x in a):
    pass

if you care about the number of repeated elements, this option seems nice, and you could optimize it sorting c and using bisect:

def all_in(a, b)
    try:
        c = b[:]
        for x in a: c.remove[x]
        return True
    except:
        return False
fortran