Tuesday 15 April 2014

python - Find item in list by type -



python - Find item in list by type -

i have list can contain several elements of different types. need check if in list there 1 or more elements of specific type , index.

l = [1, 2, 3, myobj, 4, 5]

i can accomplish goal iterate on list , check type of each element:

for i, v in enumerate(l): if type(v) == mytype: homecoming

is there more pythonic way accomplish same result?

you can utilize next , generator expression:

return next(i i, v in enumerate(l) if isinstance(v, mytype)):

the advantage of solution is lazy current one: check many items necessary.

also, used isinstance(v, mytype) instead of type(v) == mytype because preferred method of typechecking in python. see pep 0008.

finally, should noted solution raise stopiteration exception if desired item not found. can grab try/except, or can specify default value return:

return next((i i, v in enumerate(l) if isinstance(v, mytype)), none):

in case, none returned if nil found.

python list search types

No comments:

Post a Comment