Slice confusion : a[n:p] is a list exclude the last element p

Dave Benjamin ramen at lackingtalent.com
Tue Apr 29 02:34:30 EDT 2003


In article <UXara.22428$K35.745468 at news2.tin.it>, Alex Martelli wrote:
> "How many items does XX[a:b] have?"
> 
> With Python's design (following Koenig's principle), the normal
> answer (when a and b are both within XX'x boundaries) is:
>         b - a
> 
> If the last-bound had been deemed to be included, it would have been:
>         b - a + 1
> 
> Now, that innocuous-looking "+ 1" there is the cause of untold misery
> in programming -- the root of most "off-by-one" errors.  By removing
> the need for it, Koenig's principle makes you more productive.

Interesting! I've never heard that before. Thanks for the explanation.

I've definitely been bitten by this when trying to treat a 1D array as a 2D
array by multiplying rowcounts. It's even more confusing when it's not + 1
anymore, it's + something else... or is it minus? Ahhh!

In recovery,
Dave




More information about the Python-list mailing list