Why can't slice use non-int. indices?

Christopher A. Craig com-nospam at ccraig.org
Fri Jun 1 08:45:32 EDT 2001

"Ben Wolfson" <wolfson at uchicago.edu> writes:

> For that matter, why doesn't this work?
> >>> lst = range(10)
> >>> slc = slice(2,6)
> >>> lst[slc]
> Traceback (most recent call last):
>   File "<pyshell#2>", line 1, in ?
>     lst[slc]
> TypeError: sequence index must be integer
> Seems like it ought to.

foo[start:stop] calls foo.__getslice__(start, stop) while
foo[start:stop:step] calls foo.__getitem__(slice(start, stop, step))

The PySequence_GetItem function takes an integer as its second
argument (key), so it cannot accept a slice object.  The difference in
the extended versus simple slicing is caused by the fact that the extended
slice syntax was imported from Numeric and the simple version had to be
maintained for backwards compatibility.  

Christopher A. Craig <com-nospam at ccraig.org>
"When all else fails, read the instructions."

More information about the Python-list mailing list