Questions regarding design decisions in listobject.c

Thomas Wouters thomas at xs4all.net
Sun Jun 4 17:06:08 EDT 2000


On Sun, Jun 04, 2000 at 08:19:10PM +0000, Courageous wrote:

> 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?

I believe this was done to avoid having to use a lot of len() and 'or''s
inside indexes. If you want the first ten characters, or less, of a string,
currently you do:

s[:10]

If slicing raised IndexError, you'd have to do:

s[:(len(s) > 10 and 10 or len(s))] 

or wrap the entire thing in an if/else:

slen = len(s)
if slen < 10:
	substring = s[:slen]
else:
	substring = s[:10]

I believe it was decided, for the sake of simplicity, to make slices
'special' in that regard. It also fits fairly well with the 'gaps' thing
(see below), as a sequence of length 10 might not have items beyond the 10th
one, but it does have gaps, all the way into infinity ;) 

However, I Aint Guido, and I dont presume to channel Guido, so I may be
completely wrong.

> 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?

Actually, it's very intuitive, if you see the start and end index of the
slice not as items, but as the gaps between the items. In s[0:1] 0 is the
gap before the first item, 1 the gap between the first and the second item,
and so s[0:1] captures exactly one item, the first. This is a fairly
frequently asked question, by the way, but I can't find it in the FAQ...
Anyone know if it's in there or not, and if not, maybe someone can add it ?
I'm still wrestling with the overseas payment :P

Creditcard-less-European-ly yr's,
-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list