negative stride list slices
Christopher Koppler
klapotec at chello.at
Wed Sep 1 22:03:33 EDT 2004
On Wed, 01 Sep 2004 14:57:57 -0700, Shalabh Chaturvedi wrote:
> Shalabh Chaturvedi wrote:
>
>> I'd like to add:
>>
>> +---+---+---+---+---+
>> | H | e | l | p | A |
>> +---+---+---+---+---+
>> 0 1 2 3 4 5
>> -5 -4 -3 -2 -1
>> | |
>> start end (defaults for +ve step)
>> end start (defaults for -ve step)
>>
>> (Is this correct?)
>
> Apparently not.
That should be
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
| |
start end (defaults for +ve step)
end start (defaults for -ve step)
>
> >>> "HelpA"[-1:-2:-1]
> 'A'
>
> I would expect 'p'. Also,
>
> >>> "HelpA"[:-1:-1]
> ''
>
> And I definitely expected 'A'. Now I find it confusing too.
>
> Does anyone else find it intuitive to expect that S[b:a:-1] be exactly
> reverse of S[a:b:1]?
As others have explained, that's not easily possible because of Python's
zero-based indexing, which in general is great, but can lead to confusion
because using negative strides indices begin with -1.
>
> This is only true for S[::1] and S[::-1]. In other cases, for -ve step,
> the -ve indices seem to indicate a shifted position. I'm using Python 2.3.3.
The defaults here map to S[0:len(S):1] and S[-1:-len(S)-1:-1].
--
Christopher
More information about the Python-list
mailing list