osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

curious asymmetry in range limiting


On 03/20/2018 03:21 PM, Robin Becker wrote:
> I don't know how I never came across this before, but there's a curious asymmetry in the way ranges are limited
> 
> Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>   >>> s = '0123456789'
>   >>> print(repr(s[-5:5]))
> ''
>   >>> print(repr(s[5:15]))
> '56789'
>   >>>
> 
> why is the underflow start index treated so differently from the limit index overflow? I suppose there must be some reason, but it
> eludes me.
> 

It's because in the slice [-5:5] the -5 is not trying to access an 
element at an index < 0, but indicating the fifth-last element in the 
sequence.