How to raise the index index when slice indexes are out of range?

The Python documentation states that

slice indices are silently truncated to fall within the valid range

and so when the list is split, the value is promoted IndexErrors

, no matter what parameters are start

or stop

are used:

>>> egg = [1, "foo", list()]
>>> egg[5:10]
[]

      

Since the list egg

contains no indexes greater than 2

, the call egg[5]

or egg[10]

calls IndexError

:

>> egg[5]
Traceback (most recent call last):
IndexError: list index out of range

      

The question is, how can we raise IndexError

when both given slice indices are out of range?

+3


source to share


2 answers


There is no silver bullet here; you will need to check both bounds:

def slice_out_of_bounds(sequence, start=None, end=None, step=1):
    length = len(sequence)
    if start is None:
        start = 0 if step > 1 else length
    if start < 0:
        start = length - start
    if end is None:
        end = length if step > 1 else 0
    if end < 0:
        end = length - end
    if not (0 <= start < length and 0 <= end <= length):
        raise IndexError()

      



Since the end value in the cut is exceptional, it is allowed to go up to length

.

+1


source


In Python 2, you can override the method __getslice__

like this:

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 list

:

>>> egg = [1, "foo", list()]
>>> egg = MyList(egg)
>>> egg[5:10]
Traceback (most recent call last):
IndexError: list index out of range

      

+1


source







All Articles