python - finding string in a list and return it index or -1 -


defining procedure return index of item or -1 if item not in list

def ser(a,b):     j in a:         if j == b:             return (a.index(b))         else:             return -1  print (ser([1,2,3],3)) 

it's return me -1. if cut 'else' part, works. why ?

that because first time not match condition in loop return , leave method. need re-think logic here determine want when don't match. ultimately, want continue looping until have exhausted checks.

so, set return -1 outside of loop. if go through entire loop, have not found match, can return -1

def ser(a,b):     j in a:         if j == b:             return (a.index(b))     return -1  print (ser([1,2,3],3)) 

alternatively, loop can avoided using in. so, can re-write method this:

def ser(a, b):     if b in a:         return a.index(b)     return -1 

you checking see if item b in list a, if is, return index, otherwise return -1

to take simplification further, can set in single line in return:

def ser(a, b):     return a.index(b) if b in else -1 

Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -