Page David
Page David

Reputation: 1413

How to check if all elements in a tuple or list are in another?

For example, I want to check every elements in tuple (1, 2) are in tuple (1, 2, 3, 4, 5). I don't think use loop is a good way to do it, I think it could be done in one line.

Upvotes: 11

Views: 15185

Answers (4)

MikeSchneeberger
MikeSchneeberger

Reputation: 525

Since your question is specifically targeted at tuples/lists and not sets, I would assume you include cases where elements are repeated and the number of repetition matters. For example (1, 1, 3) is in (0, 1, 1, 2, 3), but (1, 1, 3, 3) is not.

import collections

def contains(l1, l2):
    l1_cnt = set(collections.Counter(l1).items())
    l2_cnt = set(collections.Counter(l2).items())

    return l2_cnt <= l1_cnt

# contains((0, 1, 2, 3, 4, 5), (1, 2)) returns True
# contains((0, 1, 1, 2, 3), (1, 1, 3)) returns True
# contains((0, 1, 1, 2, 3), (1, 1, 3, 3)) returns False

Upvotes: 0

Ahasanul Haque
Ahasanul Haque

Reputation: 11164

I think you want this: ( Use all )

>>> all(i in (1,2,3,4,5) for i in (1,2))
True 

Upvotes: 6

Sede
Sede

Reputation: 61293

You can use set.issubset or set.issuperset to check if every element in one tuple or list is in other.

>>> tuple1 = (1, 2)
>>> tuple2 = (1, 2, 3, 4, 5)
>>> set(tuple1).issubset(tuple2)
True
>>> set(tuple2).issuperset(tuple1)
True

Upvotes: 23

isopropylcyanide
isopropylcyanide

Reputation: 425

Another alternative would be to create a simple function when the set doesn't come to mind.

def tuple_containment(a,b):
    ans = True
    for i in iter(b):
        ans &= i in a
    return ans

Now simply test them

>>> tuple_containment ((1,2,3,4,5), (1,2))
True
>>> tuple_containment ((1,2,3,4,5), (2,6))
False

Upvotes: -2

Related Questions