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

4

11

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.

Underachieve answered 26/12, 2015 at 6:9 Comment(3)
Are the tuples sorted?Pechora
Are you only asking about the case where all elements are integers? and moreover, sorted in-order? (so that the order of the tuple doesn't matter?) Do you want to return True or False for testing (2,1) in (5,3,1,4,2)? Can you please show several more examples with expect output value?Seep
And if the all elements are contiguous integers, you can use a data structure like slice which only needs to test its lower- and upper-bound (start, stop and step, you don't even need a tuple/set. Or itertools.isliceSeep
R
23

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
Rotl answered 26/12, 2015 at 6:14 Comment(0)
S
6

I think you want this: ( Use all )

>>> all(i in (1,2,3,4,5) for i in (1,2))
True 
Steakhouse answered 26/12, 2015 at 6:54 Comment(0)
M
0

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
Mandrill answered 19/7, 2022 at 9:14 Comment(0)
D
-2

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
Disclaim answered 26/12, 2015 at 6:31 Comment(2)
And I clearly mentioned that mine is when the obvious doesn't come to mindDisclaim
What does tuple_checker do? Check for equality, containment, or just whether they are tuples?Pechora

© 2022 - 2024 — McMap. All rights reserved.