Reputation: 823
Is there an easy way to check if a specific type of object exists in a tuple
?
There only way I can think is to iterate over the tuple
and check every object, but knowing python I feel like there has to be a better way.
Upvotes: 0
Views: 174
Reputation: 3859
type_you_are_checking_for in map(lambda x: type(x), your_objects_tuple)
examples:
>>> str in map(lambda x: type(x), (1, "sfds"))
True
>>> str in map(lambda x: type(x), (1, 2))
False
Upvotes: 0
Reputation: 23490
I can't think of a better way than list comprehensions.
result = [x for x in mylist if type(x) is bool]
If anyone got a better solution I'm eager to see it.
But I'm betting my right sock on the fact that there's no other way than to involve a loop in any shape or form. In this case, a for
loop.
Just because I got a nifty downvote without an explanation, here's a benchmark of the alternatives given thus far, and these are the median runtime results:
type() check: 0.837047815322876
isinstance() check: 0.84004807472229
any() check: 0.8540489673614502
Code is rather crude, but here's the gist of the test.
I really don't see why this list comprehension thing would be bad, or wrong in any way.
Again, the test is crude and maybe not perfect.
But hopefully I didn't mess up the useage of any()
or any yield operators that I didn't think of.
Upvotes: 4
Reputation: 13743
This should work:
if any(map(lambda x: isinstance(x, SomeClass), my_tuple)):
# do stuff
Upvotes: 0
Reputation: 77850
At the root of the problem you do have to iterate over the list. However, there are tools to make this easy, such as
if any(isinstance(x, <class>) for x in my_list):
At least this will short-circuit when you find the first one.
Upvotes: 5