Negative array indicies and slice()

Oscar Benjamin oscar.j.benjamin at gmail.com
Mon Oct 29 20:04:22 EDT 2012


On 29 October 2012 23:01, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Mon, Oct 29, 2012 at 9:20 AM, Andrew Robinson
> <andrew3 at r3dsolutions.com> wrote:
>> FYI: I was asking for a reason why Python's present implementation is
>> desirable...
>>
>> I wonder, for example:
>>
>> Given an arbitrary list:
>> a=[1,2,3,4,5,6,7,8,9,10,11,12]
>>
>> Why would someone *want* to do:
>> a[-7,10]
>> Instead of saying
>> a[5:10] or a[-7:-2] ?
>
> A quick search of local code turns up examples like this:
>
> if name.startswith('{') and name.endswith('}'):
>     name = name[1:-1]
>
> If slices worked like ranges, then the result of that would be empty,
> which is obviously not desirable.
>
> I don't know of a reason why one might need to use a negative start
> with a positive stop, though.

It's useful when getting a reversed slice:

>>> a = [1,2,3,4,5,6,7,8,9,10]
>>> a[-3:3:-1]
[8, 7, 6, 5]


Oscar



More information about the Python-list mailing list