rreichel
rreichel

Reputation: 823

Determine if specific type of object exists in a tuple

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

Answers (4)

gipsy
gipsy

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

Torxed
Torxed

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.

  1. It checks for a specific type (as requested)
  2. You get a list of all the elements that is of that type
  3. It's faster than the alternatives?

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

Tonechas
Tonechas

Reputation: 13743

This should work:

if any(map(lambda x: isinstance(x, SomeClass), my_tuple)):
    # do stuff

Upvotes: 0

Prune
Prune

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

Related Questions