Questions regarding design decisions in listobject.c

Remco Gerlich scarblac-spamtrap at pino.selwerd.nl
Mon Jun 5 07:47:06 EDT 2000


Courageous wrote in comp.lang.python:
> 1. For slice operations, ilow/ihigh indices which undeflow
> or overflow the list in question are reset to the edges
> of the list. Why was it that PyExc_IndexError wasn't
> thrown instead?

Much more easy to use, I suppose. a slice[a:b] returns all elements of which
the index has a <= index < b.

> 2. In slice expressions of the form s[i:j], what was the
> design decision that lead to s[i:i] always returning an
> empty list and s[i:i+1] selecting one item. At first
> glance, it would appear that s[i:i] is the obvious and
> intuitive correct expression to return just one item on
> a slice, where s[i:i+1] ought to select two items and so
> forth. Was there some particular situation which arose
> which required this slightly counterintuitive idiom?

This is symmetrical to the behaviour of range(). range(i,i) also returns an
empty list. The same arguments apply.

At first sight, this is counterintuitive. At second and all further sights,
this is the best behaviour.

If you have a list s of length n, s[:n] has the whole list, s[:n-1] is all
but one element, etc (s[:-1] is basically sugar for s[:n-1]).

The slice s[a:b] always tries to grab exactly b-a items.

For a list s of length m, with 0<=m<=n, s == s[:m]+s[m:]

For a list s of length n, and integers a,b,...,z where 0<=a<=b<=...<=z<=n,
s == s[:a]+s[a:b]+s[b:c]+...+s[y:z]+s[z:]
;-)

In short, it makes *loads* of off-by-one errors just disappear.

-- 
Remco Gerlich,  scarblac at pino.selwerd.nl
"Early to rise, early to bed, makes a man healthy, wealthy and dead." -- TP



More information about the Python-list mailing list