“List index out of range” error occurs in Python when we try to access an undefined element from the list. The only way to avoid this error is to mention the indexes of list elements properly.
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.
The elements in the set are immutable(cannot be modified) but the set as a whole is mutable. There is no index attached to any element in a python set. So they do not support any indexing or slicing operation.
To solve the “index error: list index out of range” error, you should make sure that you're not trying to access a non-existent item in a list. If you are using a loop to access an item, make sure that the loop accounts for the fact that lists are indexed from zero.
There is nothing "dirty" about using try-except clause. This is the pythonic way. ValueError
will be raised by the .index
method only, because it's the only code you have there!
To answer the comment:
In Python, easier to ask forgiveness than to get permission philosophy is well established, and no index
will not raise this type of error for any other issues. Not that I can think of any.
thing_index = thing_list.index(elem) if elem in thing_list else -1
One line. Simple. No exceptions.
The dict
type has a get
function, where if the key doesn't exist in the dictionary, the 2nd argument to get
is the value that it should return. Similarly there is setdefault
, which returns the value in the dict
if the key exists, otherwise it sets the value according to your default parameter and then returns your default parameter.
You could extend the list
type to have a getindexdefault
method.
class SuperDuperList(list):
def getindexdefault(self, elem, default):
try:
thing_index = self.index(elem)
return thing_index
except ValueError:
return default
Which could then be used like:
mylist = SuperDuperList([0,1,2])
index = mylist.getindexdefault( 'asdf', -1 )
If you are doing this often then it is better to stow it away in a helper function:
def index_of(val, in_list):
try:
return in_list.index(val)
except ValueError:
return -1
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