Slicing beyond list -- bug or featurette?

Tim Peters Tim.Peters at p98.f112.n480.z2.fidonet.org
Sat Jul 3 06:37:59 EDT 1999


From: "Tim Peters" <tim_one at email.msn.com>

[Pierre Fortin]
> Just ran into a situation which can be summarized as follows:
>
> list = [ 0,1,2,3,4 ]
>
> list[<0..4>] returns the appropriate item
>
> list[m] where m is >= len(list) expectedly fails
>
> list[2:50] returns [ 2,3,4 ]
> list[20:] or list[20:30] returns []
>
> Can I count on this, or should I code try/except for the day it's
> fixed?

It's guaranteed by footnote 2 to the table in the Library Ref's section
2.1.5 (Sequence Types).  I think the Language Ref leaves it open to debate,
though (if anything ever changes here, it's almost certainly that the
Language Ref will get more words blessing the current implementation).

> This 'feature' reduces the error situations; but is it correct/intended?

All three <wink>.  Slicing returns a subsequence, and the possibility to
return an empty subsequence works out very smoothly in practice.

More dubious is that negative indices index "from the right end":

    x[-1] == x[len(x)-1]

This is too handy to give up, but in my experience *has* let some errors
slip by; while I can't recall any case where

    x[insane_1 : insane_2] == []

didn't simply handle an expected endcase gracefully.  Doesn't mean we
couldn't construct one, just saying I've never seen one occur naturally.

BTW, in some older code you may see the strange idiom

    prefix[sys.maxint:] = suffix

or more likely

    prefix[HUGE:] = suffix

in a loop where HUGE = sys.maxint is computed once outside the loop.  In
1.5.2 it's spelled

    prefix.extend(suffix)

the-set-of-all-i-less-than-2-where-i-greater-than-100-is-just-empty-ly
'rs  - tim







More information about the Python-list mailing list