moby moby - 3 months ago 8x
Python Question

Python index of item in list without error?

Possible Duplicate:

Python list.index question

To find the index of an item in a list, you use:

Return the index in the list of the first item whose value is x.
It is an error if there is no such item.

That seems a little odd to me, that it would throw an error if the item wasn't found. Where I come from (Objective-C land), it returns a NSNotFound enum (which is just a max int, indicating the item wasn't found).

So I made something ugly to go around this:

index = 0
for item in self.items:
if == desired_id:
return index
index = index + 1
return -1

I used -1 to indicate the item wasn't found. What's a better way to do this, and why doesn't Python have something like this built in?

a = [1]
    index_value = a.index(44)
except ValueError:
    index_value = -1

How about this?