Slice confusion : a[n:p] is a list exclude the last element p
Alex Martelli
aleax at aleax.it
Tue Apr 29 08:16:55 EDT 2003
Dave Benjamin wrote:
> 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
Hmmm, I had let my enthusiasm take over here a bit -- make that "many"
rather than "most"!-)
>> the need for it, Koenig's principle makes you more productive.
>
> Interesting! I've never heard that before. Thanks for the explanation.
You're welcome!
> 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!
Oh yes -- and languages where array indexing starts at ONE, rather than
at zero, are even more HORRID that way!
Alex
More information about the Python-list
mailing list