Given a list [\"foo\", \"bar\", \"baz\"]
and an item in the list \"bar\"
, how do I get its index (1
) in Python?
All of the proposed functions here reproduce inherent language behavior but obscure what's going on.
[i for i in range(len(mylist)) if mylist[i]==myterm] # get the indices
[each for each in mylist if each==myterm] # get the items
mylist.index(myterm) if myterm in mylist else None # get the first index and fail quietly
Why write a function with exception handling if the language provides the methods to do what you want itself?