Is there a way to check if an instance of a specific data type is present in a list / dictionary, without explicitly checking every element / key?
I suspect the answer is no. If it does exist, though, I imagine it would be similar to the way you can use the in
operator to search for specific elements / keys, like this:
3 in [1, 2, 3] # => True
except you'd be checking for an instance of a data type rather than a some specific value, like this:
int in [1,"a", 3.4] # => True
Any ideas?
Well in
is actually syntactic sugar for __contains__
, which does iterate over the contents of the list.
If you would like to use in
to check for types instead; you could implement your own data structure (subclassing list
) and override __contains__
to check for types:
class MyList(list):
def __contains__(self, typ):
for val in self:
if isinstance(val, typ):
return True
return False
x = MyList([1, 2, 'a', 3])
print float in x # False
print str in x # True
You could also take advantage of the any function:
def __contains__(self, typ):
return any(isinstance(val, typ) for val in self)
print int in MyList([1, "a", 3.4]) # True
print int in MyList(["a", 3.4]) # False
As for whether this is doable without checking every element - no, it's not. In the worst case scenario, you do end up checking every element.