I have a list that can contain several elements of different types. I need to check if in this list there is one or more elements of a specific type and get its index.
l = [1, 2, 3, myobj, 4, 5]
I can achieve this goal by simply iterate over my list and check the type of each element:
for i, v in enumerate(l):
if type(v) == Mytype:
return i
Is there a more pythonic way to accomplish the same result?
You can use next and a generator expression:
return next(i for i, v in enumerate(l) if isinstance(v, Mytype)):
The advantage of this solution is that it is lazy like your current one: it will only check as many items as are necessary.
Also, I used isinstance(v, Mytype) instead of type(v) == Mytype because it is the preferred method of typechecking in Python. See PEP 0008.
Finally, it should be noted that this solution will raise a StopIteration exception if the desired item is not found. You can catch this with a try/except, or you can specify a default value to return:
return next((i for i, v in enumerate(l) if isinstance(v, Mytype)), None):
In this case, None will be returned if nothing is found.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With