curious about slice behaviour

T

Terry Reedy

Stephan Diehl said:
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
 
S

Stephan Diehl

Stephan Diehl said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top