Extended slicing and Ellipsis - where are they used?

James Stroud jstroud at mbi.ucla.edu
Thu Sep 13 20:50:06 EDT 2007


Rodney Maxwell wrote:
> The following are apparently legal Python syntactically:
>    L[1:3, 8:10]
>    L[1, ..., 5:-2]
> 
> But they don't seem to work on lists:
>>>> l = [0,1,2,3]
>>>> l[0:2,3]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: list indices must be integers
>>>> l[...]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: list indices must be integers
> 
> So where is this extended slicing used?

AFAICT this syntax is not used in the standard library. However, the 
mega-beauty of it is that you can make use of it in your own classes:

py> class Bob(list):
...   def __getitem__(self, i):
...     try:
...       return [list.__getitem__(self, j) for j in i]
...     except TypeError:
...       return list.__getitem__(self, i)
...
py> b = Bob(xrange(15, 30))
py> b[3, 5, 7, 13]
[18, 20, 22, 28]

James



More information about the Python-list mailing list