curious about slice behaviour

Terry Reedy tjreedy at udel.edu
Mon Sep 5 14:26:14 EDT 2005


"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'
>>>> 'test'[40:50]
> ''
> I'd rather expected to be confronted with an IndexError.
> (This is actually described in
> http://docs.python.org/lib/typesseq.html,

in footnote 4

>.so my expectation was wrong :))
> 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.

Terry J. Reedy






More information about the Python-list mailing list