Question

How can I do this?

A = ['fish', 'banana', 'old pajamas', 'Mutton', 'Beef', 'Trout']
B = ['fish', 'banana', 'old pajamas']

B in A = True
A in B = False

I tried the 'in' comparator, but it returns False in both cases because it's checking if the List B is inside the List A and not the items of B in A.

Is there a easy way to do this beside using a very long if statement like this:

if B[0] == A[0] and B[1] == A[1] and B[2] == A[2]: 
    return True
else: return False
Was it helpful?

Solution

In [8]: all(a==b for a,b in zip(A,B))
Out[8]: True

is equivalent to

if B[0] == A[0] and B[1] == A[1] and B[2] == A[2]: 
    return True
else: return False

since zip terminates when there are no more elements in the shorter of A or B:

In [9]: zip(A, B)
Out[9]: [('fish', 'fish'), ('banana', 'banana'), ('old pajamas', 'old pajamas')]

If, on the other hand, you wish to test if all the elements of A are in B, then you are looking for a subset relationship. If you convert A and B to sets, then you could use its <= operator:

In [12]: set(B) <= set(A)
Out[12]: True

since B is a subset of A.

In [13]: set(A) <= set(B)
Out[13]: False

since A is not a subset of B.


Edit: As Aशwini चhaudhary points out, sets also have an issubset method:

In [42]: set(B).issubset(A)
Out[42]: True

In [43]: set(A).issubset(B)
Out[43]: False
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top