Find an item in a list by type
I have a list that can contain several elements of different types. I need to check if this list has one or more elements of a certain type and get its index.
l = [1, 2, 3, myobj, 4, 5]
I can achieve this goal by simply traversing my list and checking the type of each element:
for i, v in enumerate(l):
if type(v) == Mytype:
return i
Is there a more pythonic way to achieve the same result?
You can use a generatornext
expression as well :
return next(i for i, v in enumerate(l) if isinstance(v, Mytype)):
The advantage of this solution is that it is as lazy as your current one: it will only check as many elements as needed.
Also, I used isinstance(v, Mytype)
instead type(v) == Mytype
because that is the preferred method of type checking in Python. See PEP 0008 .
Finally, it should be noted that this solution will raise an exception StopIteration
if the required element is not found. You can catch this with try / except, or you can provide a default return value:
return next((i for i, v in enumerate(l) if isinstance(v, Mytype)), None):
In this case, it None
will be returned if nothing was found.
You can use a list comprehension.
Get all elements of a string like:
b = [x for x in a if isinstance(x,str)]
Get all indices of elements of a string of type:
b = [x[0] for x in enumerate(a) if isinstance(x[1],str)]