The Python Documentation states that
slice indices are silently truncated to fall in the allowed range
and therefor no IndexErrors
are risen when slicing a list, regardless what start
or stop
parameters are used:
>>> egg = [1, "foo", list()]
>>> egg[5:10]
[]
Since the list egg
does not contain any indices greater then 2
, a egg[5]
or egg[10]
call would raise an IndexError
:
>> egg[5]
Traceback (most recent call last):
IndexError: list index out of range
The question is now, how can we raise an IndexError
, when both given slice indices are out of range?
The slicing operation doesn't raise an error if both your start and stop indices are larger than the sequence length. This is in contrast to simple indexing—if you index an element that is out of bounds, Python will throw an index out of bounds error. However, with slicing it simply returns an empty sequence.
IndexError: list index out of range error thrown. So the error is thrown when i is equal to 3 because there is no item with an index of 3 in the list. To fix this problem, we can modify the condition of the loop by removing the equal to sign. This will stop the loop once it gets to the last index.
Using an index number that is out of the range of the list. You'll get the Indexerror: list index out of range error when you try and access an item using a value that is out of the index range of the list and does not exist.
This index error is triggered when indexing a list using a value outside of its range of indexes. The best way to avoid it is by carefully considering what range of indexes a list might have, taking into account that list indexes start at zero instead of one.
In Python 2 you can override __getslice__
method by this way:
class MyList(list):
def __getslice__(self, i, j):
len_ = len(self)
if i > len_ or j > len_:
raise IndexError('list index out of range')
return super(MyList, self).__getslice__(i, j)
Then use your class instead of list
:
>>> egg = [1, "foo", list()]
>>> egg = MyList(egg)
>>> egg[5:10]
Traceback (most recent call last):
IndexError: list index out of range
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