Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python index of item in list without error? [duplicate]

Tags:

python

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

list.index(x) 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 item.id == 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?

like image 580
Snowman Avatar asked Oct 31 '12 14:10

Snowman


People also ask

How do I find the index of a duplicate element in a list?

Method #1 : Using loop + set() In this, we just insert all the elements in set and then compare each element's existence in actual list. If it's the second occurrence or more, then index is added in result list.

How do you find the index of a value in a list Python?

To find the index of an element in a list, you use the index() function. It returns 3 as expected. However, if you attempt to find an element that doesn't exist in the list using the index() function, you'll get an error.

What does .index return if not found?

The index() method searches for the first occurrence of the given item and returns its index. If specified item is not found, it raises 'ValueError' exception. The optional arguments start and end limit the search to a particular subsequence of the list.


2 Answers

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

How about this?

like image 83
Jakob Bowyer Avatar answered Sep 19 '22 23:09

Jakob Bowyer


It's not a good idea to return -1 as that is a valid index in Python (see Python list.index throws exception when index not found).

Probably best to catch the index error and act accordingly.

like image 45
doc Avatar answered Sep 18 '22 23:09

doc