curious about slice behaviour
Stephan Diehl
stephan.diehl at gmx.net
Mon Sep 5 14:41:27 EDT 2005
On Mon, 05 Sep 2005 14:26:14 -0400, Terry Reedy wrote:
>
> "Stephan Diehl" <stephan.diehl at gmx.net> wrote in message
> news:pan.2005.09.05.17.06.41.434180 at gmx.net...
>>I just found out by accident, that slice indices can be larger than
>> the length of the object. For example
>>>>> 'test'[:50]
>> 'test'
[...]
>> Does anybody know, why this is preferred to just raising an error?
>
> Slicing was intentially designed to always give an answer (given int
> coords) and never say 'can't answer' (whether by exception or a None
> return). This avoids having to call len() when you don't care and avoids
> having to use try:...except:... or conditionalize the code when it is not
> needed. For instance c=s[0:1] is equivalent to
>
> c=s[0:min(1,len(s))] # if slice had to be exact, or
>
> c = s and s[0] or '' # or
>
> if s:
> c = s[0]
> else:
> c = '' # or
>
> try:
> c = s[0]
> except IndexError:
> c = ''
>
> People occasionally post buggy code which simply needs s[0] changed to
> s[0:1].
>
> The form s[i:], which I am sure you agree is useful, is effectively
> equivalent to eithers[i:len(s)] or s[i:<maxint>]. The latter view
> generalizes to iterables without a knowable length.
I do think that this is useful and can save some lines of code.
Just never expected this.
>
> Terry J. Reedy
More information about the Python-list
mailing list