a simple question about the third index in slice

7 views
Skip to first unread message

700MHz

unread,
Oct 21, 2005, 2:23:50 AM10/21/05
to python
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?
Thanks!

zavandi

unread,
Oct 21, 2005, 4:26:11 AM10/21/05
to pyt...@googlegroups.com
In a[1::-1] the end offset is 0 (or rather -1), because the step is
negative. a[1:10:-1] means chars from index 1 (inclusive) to 10
(non-inclusive), going backwards, so it's the empty string. a[10:1:-1]
would've meant chars from index 10 (inclusive) to 1 (non-inclusive),
going backwards, so it's '98765432'.

700MHz

unread,
Oct 30, 2005, 1:18:57 AM10/30/05
to python

zavandi wrote:

> In a[1::-1] the end offset is 0 (or rather -1), because the step is
> negative. a[1:10:-1] means chars from index 1 (inclusive) to 10
> (non-inclusive), going backwards, so it's the empty string. a[10:1:-1]
> would've meant chars from index 10 (inclusive) to 1 (non-inclusive),
> going backwards, so it's '98765432'.

Thank you!

Reply all
Reply to author
Forward
0 new messages