Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise an IndexError when slice indices are out of range?

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?

like image 789
elegent Avatar asked Aug 07 '15 09:08

elegent


People also ask

What happen if you use out of range index with slicing?

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.

How do I resolve IndexError list index out of range?

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.

What happens if index is out of range?

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.

How do you prevent index out of range error?

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.


1 Answers

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
like image 145
Vladimir Chub Avatar answered Oct 14 '22 03:10

Vladimir Chub