I have a list of integers. I want to know whether the number 13 appears in it and, if so, where. Do I have to search the list twice, as in the code below?
if 13 in intList:
i = intList.index(13)
In the case of dictionaries, there's a get
function which will ascertain membership and perform look-up with the same search. Is there something similar for lists?
You answered it yourself, with the index()
method. That will throw an exception if the index is not found, so just catch that:
def getIndexOrMinusOne(a, x):
try:
return a.index(x)
except ValueError:
return -1
It looks like you'll just have to catch the exception...
try:
i = intList.index(13)
except ValueError:
i = some_default_value
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