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.
How to check if all elements in a tuple or list are in another?
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
I think you want this: ( Use all )
>>> all(i in (1,2,3,4,5) for i in (1,2))
True
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
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
And I clearly mentioned that mine is when the obvious doesn't come to mind –
Disclaim
What does
tuple_checker
do? Check for equality, containment, or just whether they are tuples? –
Pechora © 2022 - 2024 — McMap. All rights reserved.
slice
which only needs to test its lower- and upper-bound (start
,stop
andstep
, you don't even need a tuple/set. Oritertools.islice
– Seep