a simple question about the third index in slice

Fredrik Lundh fredrik at pythonware.com
Fri Oct 21 02:41:13 EDT 2005


someone wrote:

> I cannot quite understand when the third index is a negative
> number,like this:
> a = '0123456789'
> a[1:10:2] I know the index step is 2, so it will collect items from
> offset 1, 3, 5, 7, 9
> but when a negative number come,like:
> a[1::-1] answer '10', and a[1:10:-1] only answer '',
> what is the different between the two expression, where does the offset
> begin and what is the end offset?

the default values for start and stop depend on the sign of the step.

you can use the slice type directly to see how this works:

>>> slice(None,None,1).indices(10)
(0, 10, 1)
>>> slice(None,None,-1).indices(10)
(9, -1, -1)

>>> slice(1,None,-1).indices(10)
(1, -1, -1)
>>> slice(1,10,-1).indices(10)
(1, 10, -1)

also see footnote 5 on this page:

    http://docs.python.org/lib/typesseq.html

</F>






More information about the Python-list mailing list