Do Python lists have the equivalent of dict.get?

I have a list of integers. I want to know if the number 13 appears in it, and if so, where. Should I search the list twice, as in the code below?

if 13 in intList: i = intList.index(13) 

There is a get function in dictionaries that will determine membership and perform a search with the same search. Is there something similar for lists?

+7
python list
source share
5 answers

You yourself answered using the index() method. This will throw an exception if the index is not found, so just catch this:

 def getIndexOrMinusOne(a, x): try: return a.index(x) except ValueError: return -1 
+12
source share

Looks like you just need to catch the exception ...

 try: i = intList.index(13) except ValueError: i = some_default_value 
+7
source share

No, there is no direct correspondence to what you requested. A discussion was posted on the Python mailing list, and people came to the conclusion that it was probably the smell of code if you needed it. Consider using dict or set instead if you need to verify membership this way.

+3
source share

You can catch a ValueError exception, or you can do:

 i = intList.index(13) if 13 in intList else -1 

(Python 2.5+)

BTW. if you are going to do a large batch of such operations, you might consider creating an inverse dictionary value -> index.

 intList = [13,1,2,3,13,5,13] indexDict = defaultdict(list) for value, index in zip(intList, range(len(intList))): indexDict[value].append(index) indexDict[13] [0, 4, 6] 
+2
source share

Just enter what you have in the function and use it :)

You can use if i in list: return list.index(i) or try/except , depending on your preference.

-one
source share

All Articles