python for loop

Chris Rebert clp2 at rebertia.com
Wed Apr 1 02:58:09 CEST 2009


On Tue, Mar 31, 2009 at 5:48 PM, Lada Kugis <lada.kugis at gmail.com> wrote:
> On Wed, 01 Apr 2009 11:42:20 +1100, Ben Finney
> <ben+python at benfinney.id.au> wrote:
>
>>Lada Kugis <lada.kugis at gmail.com> writes:
>>
>>> in python for example:
>>> for i in range(1,n)
>>> goes from 1,2,3,4,...,n-1
>>> (that is, it goes from 1 up to, but not including n)
>>
>>Also, ?range(n)? counts from 0 to n-1.
>>
>>> Why is that so ?
>>
>>The answer is in the documentation for ?range?:
>>
>>    For example, range(4) returns [0, 1, 2, 3]. The end point is
>>    omitted! These are exactly the valid indices for a list of 4
>>    elements.
>
> Yes, but why didn't they start indexing from 1 then, like fortran for
> example ?
> It would solve for [1,2,3,4] length of list (just returns the last
> indice, in this case 4), "up to and including" problem, ...

Might I suggest you read Dijkstra's famous justification for 0-numbering:
http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF

Among other things, it has the nice property that:
len(some_list[n:m]) == m-n

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com



More information about the Python-list mailing list