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?
In Python 2 you can override
__getslice__
method by this way:Then use your class instead of
list
:There is no silver bullet here; you'll have to test both boundaries:
Since the end value in slicing is exclusive, it is allowed to range up to
length
.