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?
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.
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.
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.
a = [1] try: index_value = a.index(44) except ValueError: index_value = -1
How about this?
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.
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