Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Python lists have an equivalent to dict.get?

Tags:

python

list

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?

like image 984
Tommy Herbert Avatar asked Mar 16 '09 13:03

Tommy Herbert


2 Answers

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
like image 124
unwind Avatar answered Sep 28 '22 08:09

unwind


It looks like you'll just have to catch the exception...

try:
    i = intList.index(13)
except ValueError:
    i = some_default_value
like image 29
SingleNegationElimination Avatar answered Sep 28 '22 08:09

SingleNegationElimination