Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

python for loop

47 views
Skip to first unread message

Lada Kugis

unread,
Mar 31, 2009, 8:24:45 PM3/31/09
to
I'm coming from fortran and c background so I'm certainly biased by
them. But if you could explain one thing to me:

in fortran for example:
for i=1,n
goes from 1,2,3,4,...,n

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)

Why is that so ? What were the reasons for that "not including" part ?
It troubles me greatly, and I cannot see it's advantages over the
"standard" "up to and including" n.

Best regards
Lada

Chris Rebert

unread,
Mar 31, 2009, 8:39:42 PM3/31/09
to Lada Kugis, pytho...@python.org

Because it's extremely handy when the list variable is a list index:

my_list = [1,2,3,4]
for i in range(len(my_list)):
#i goes from 0 to len(my_list)-1, which is all the indices of the list
print my_list[i]

Of course, this is a toy example which would be better written `for i
in my_list:`, but you get the point.

Cheers,
Chris

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

Ben Finney

unread,
Mar 31, 2009, 8:42:20 PM3/31/09
to
Lada Kugis <lada....@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.

You may be interested in the iterator-generating functions in
‘itertools’ <URL:http://docs.python.org/library/itertools>.

--
\ “Our products just aren't engineered for security.” —Brian |
`\ Valentine, senior vice-president of Microsoft Windows |
_o__) development |
Ben Finney

Lada Kugis

unread,
Mar 31, 2009, 8:44:26 PM3/31/09
to
On Wed, 01 Apr 2009 02:24:45 +0200, Lada Kugis <lada....@gmail.com>
wrote:

>I'm coming from fortran and c background so I'm certainly biased by
>them. But if you could explain one thing to me:
>
>in fortran for example:
>for i=1,n
>goes from 1,2,3,4,...,n

And of course, lapsus calami, this is wrong and it should go like:

do 1 i=1,n
... goes from ...

Grant Edwards

unread,
Mar 31, 2009, 8:44:45 PM3/31/09
to
On 2009-04-01, Lada Kugis <lada....@gmail.com> wrote:

> 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)
>
> Why is that so?

I'm surprised this isn't in the FAQ yet, but it doesn't seem to
be there.

> What were the reasons for that "not including" part?

So that range(n,m) behaves the same as slicing (e.g. similar to
someSequence[n:m])

Why does slicing behave that way?

So that someSequence[n:m]+someSequence[m:o] == someSequnece[n:o]

> It troubles me greatly,

Sorry about that.

> and I cannot see it's advantages over the "standard" "up to
> and including" n.

--
Grant

Lada Kugis

unread,
Mar 31, 2009, 8:48:15 PM3/31/09
to
On Wed, 01 Apr 2009 11:42:20 +1100, Ben Finney
<ben+p...@benfinney.id.au> wrote:

>Lada Kugis <lada....@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, ...

Lada

>
>You may be interested in the iterator-generating functions in

>?itertools? <URL:http://docs.python.org/library/itertools>.

Chris Rebert

unread,
Mar 31, 2009, 8:58:09 PM3/31/09
to Lada Kugis, pytho...@python.org
On Tue, Mar 31, 2009 at 5:48 PM, Lada Kugis <lada....@gmail.com> wrote:
> On Wed, 01 Apr 2009 11:42:20 +1100, Ben Finney
> <ben+p...@benfinney.id.au> wrote:
>
>>Lada Kugis <lada....@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

Gary Herron

unread,
Mar 31, 2009, 9:05:19 PM3/31/09
to pytho...@python.org
> --
> http://mail.python.org/mailman/listinfo/python-list
>
This debate has been around for decades, in both mathematics and
programming.

Should a loop through n things use indices
1, 2, ..., n
or
0, 1, ..., n-1 ?

Fortran tends to go with the former (1-based indices) , while modern
languages usually go with the latter (0-based indices). (And just for
the record, your range(1,n) seems to be trying to coerce Python from
0-based to 1-based.)

The arguments for each are many, but are often centered around the
prevalence of the proverbial off-by-one error. Here's a nice
explanation of the off-by-one error:
http://en.wikipedia.org/wiki/Off-by-one_error
Google can provide many more.


My personal view is that 0-based loops/indices is *far* more natural,
and the 1-based loops/indices are a *huge* source of off-by-one errors.
But I'm sure others will argue over that point.

Gary Herron


andrew cooke

unread,
Mar 31, 2009, 9:13:05 PM3/31/09
to Lada Kugis, pytho...@python.org
Lada Kugis wrote:
> I'm coming from fortran and
*********** c ***********

> background so I'm certainly biased by
> them. But if you could explain one thing to me:

but this is exactly the same behaviour as the standard way of doing things
in c!

int a[5];
for (i = 0; i < 5; ++i) {
a[i] = 0;
}

were you being honest about the c background?!

andrew


Steven D'Aprano

unread,
Mar 31, 2009, 9:26:41 PM3/31/09
to


Why Python (and other languages) count from zero instead of one, and
why half-open intervals are better than closed intervals:

http://www.johndcook.com/blog/2008/06/26/why-computer-scientists-count-from-zero/
http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html


--
Steven

Lada Kugis

unread,
Mar 31, 2009, 9:57:25 PM3/31/09
to
On Tue, 31 Mar 2009 18:05:19 -0700, Gary Herron
<ghe...@islandtraining.com> wrote:

>This debate has been around for decades, in both mathematics and
>programming.
>
>Should a loop through n things use indices
> 1, 2, ..., n
>or
> 0, 1, ..., n-1 ?
>
>Fortran tends to go with the former (1-based indices) , while modern
>languages usually go with the latter (0-based indices). (And just for
>the record, your range(1,n) seems to be trying to coerce Python from
>0-based to 1-based.)

Oh, don't mind those. I just bumped them off the top of my head for
purpose of comparison.

>
>The arguments for each are many, but are often centered around the
>prevalence of the proverbial off-by-one error. Here's a nice
>explanation of the off-by-one error:
> http://en.wikipedia.org/wiki/Off-by-one_error
>Google can provide many more.
>
>
>My personal view is that 0-based loops/indices is *far* more natural,
>and the 1-based loops/indices are a *huge* source of off-by-one errors.
>But I'm sure others will argue over that point.

Yes, that's it. I won't argue over it, since I can't change it, but 1
is still more natural to me (it is "the real world" way). The above
pros seem to me to be very little compared to the cons of the ... and
the (m-n) point Chris was trying to explain doesn't seem that relevant
to me.
I always thought since python is trying so hard to be as intuitive as
it can get it would be the other way (you have 1 apple, you start
counting from 1 ...

but then again, I have training of an engineer, not as an CS, so we
probably have a completely different view of looking at things.

Thank you for the explanation Gary.

Ciao,
Lada

>
>Gary Herron
>

Lada Kugis

unread,
Mar 31, 2009, 10:13:18 PM3/31/09
to

:-)
Yes, I usually avoid lyes. They are hard to remember.

In C you can do it either way, I usually use the one starting from 1
and with "=", since that way it corresponds to my paper data.
Why it troubles me so much: for example, I'm doing the FEM analysis of
a simple ... uhmm, not sure how you say this, stick or beam or girder

node 1 ******* node 2 ******* node 3

I have n=3 nodes and n-1 elements. The matrix will have 3 rank.
The indexes in the matrix correspond to the nodes, and so on.
(this is just an elementary example, but you probably understand)

If I try this in py, it goes for i in range(0,3) then it gets all
moved by one. If I go (1,4) then it ...

Lada

>andrew
>

Lada Kugis

unread,
Mar 31, 2009, 10:23:48 PM3/31/09
to
On 01 Apr 2009 01:26:41 GMT, Steven D'Aprano
<ste...@REMOVE.THIS.cybersource.com.au> wrote:

>
>Why Python (and other languages) count from zero instead of one, and
>why half-open intervals are better than closed intervals:
>
>http://www.johndcook.com/blog/2008/06/26/why-computer-scientists-count-from-zero/
>http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html

steven, thanks for answering,

yes, i saw the second one a little time ago (someone else posted it as
well in really cute handwriting version :) and the first time just
now, but the examples which both of them give don't seem to me to be
that relevant, e.g. the pros don't overcome the cons.

imho, although both sides (mathematical vs engineer) adress some
points, none of them give the final decisive argument.
i understand the math. point of view, but from the practical side it
is not good. it goes nicely into his tidy theory of everything, but
practical and intuitive it is not. as i said, being an engineer, i
tend towards the other side, so this is biased opinion (nobody can be
unbiased) but from a practical side it seems unpractical for
engineering problems (and to me, the purpose of computers is to help
humans to build a better world, not to prove theories - theories are
useless if they don't help us in reality. so we should try to adapt
computing to real world, not our world to computers).

but i just read somewhere that guido who wrote python is a mathem. so
that probably had to do with the decision.

nevertheless, thank you for the links.
you have a nice group here, i always am nicely suprised how people
tend to be helpful

nice regards
lada

Chris Rebert

unread,
Mar 31, 2009, 10:29:56 PM3/31/09
to Lada Kugis, pytho...@python.org
On Tue, Mar 31, 2009 at 7:13 PM, Lada Kugis <lada....@gmail.com> wrote:
> On Tue, 31 Mar 2009 21:13:05 -0400 (CLT), "andrew cooke"
> <and...@acooke.org> wrote:
>
>>Lada Kugis wrote:
>>> I'm coming from fortran and
>>   *********** c ***********
>>> background so I'm certainly biased by
>>> them. But if you could explain one thing to me:
>>
>>but this is exactly the same behaviour as the standard way of doing things
>>in c!
>>
>>int a[5];
>>for (i = 0; i < 5; ++i) {
>>  a[i] = 0;
>>}
>>
>>were you being honest about the c background?!
>>
>
> :-)
> Yes, I usually avoid lyes. They are hard to remember.
>
> In C you can do it either way

Sort of, but it's *really* not idiomatic. You'd have to declare the
arrays to be one longer than they actually are so that array[N] is a
valid index. And then you'd end up not using the true first element of
the array. Not to mention most library functions use 0-numbering, so
you'd have to work around that as well.

So, it can be done, but you're going against the grain of the language.

woo...@gmail.com

unread,
Mar 31, 2009, 10:30:15 PM3/31/09
to
Counting from zero through n-1 is used because it is the memory offset
and not any kind of counter. Simplified, if you are iterating through
a list, using a for loop or anything else, the first element/number is
at memory offset zero because it is at the beginning. And if this is
a list of 4 byte integers, the offset for the second element is 1*4
bytes, etc. This idea, that somehow the first element of a list is
the zero element is a fairly recent abnormality AFAIK. It perhaps
comes from assumptions by people who are not familiar with what
happens inside of a programming language, assuming incorrectly, that
the (programming) world was created in their own image, and so
programming languages were generated in the way that they think they
were. This is a bad assumption for any programmer. Instead one
should get in the habit of saying, in general as well as in this
specific case, "This doesn't make sense. I wonder how __I__ screwed
this up." Hopefully this will be helpful advice. Taking the attitude
that you have screwed up yet again will get to the heart of the
problem, and save many hours of frustration wondering why "this
language/computer doesn't do what it is supposed to do".

Lada Kugis

unread,
Mar 31, 2009, 10:37:41 PM3/31/09
to
On Tue, 31 Mar 2009 19:29:56 -0700, Chris Rebert <cl...@rebertia.com>
wrote:


>Sort of, but it's *really* not idiomatic. You'd have to declare the
>arrays to be one longer than they actually are so that array[N] is a
>valid index. And then you'd end up not using the true first element of
>the array. Not to mention most library functions use 0-numbering, so
>you'd have to work around that as well.
>
>So, it can be done, but you're going against the grain of the language.

I use fortran libraries, so that is not a problem for me. I only make
the change once, while transferring the elements ... uhmm, make that
twice.
I wrote in my other post, 0 is weird to me, I have model of solution
on paper ... if I keep 0 then all comes out different. And while
comparing, I always get them mixed up. That's why I always try to
adapt it to the paper situation.

Lada


>
>Cheers,
>Chris

Rhodri James

unread,
Mar 31, 2009, 10:59:36 PM3/31/09
to pytho...@python.org
On Wed, 01 Apr 2009 03:37:41 +0100, Lada Kugis <lada....@gmail.com>
wrote:

> On Tue, 31 Mar 2009 19:29:56 -0700, Chris Rebert <cl...@rebertia.com>
> wrote:
>
>
>> Sort of, but it's *really* not idiomatic. You'd have to declare the
>> arrays to be one longer than they actually are so that array[N] is a
>> valid index. And then you'd end up not using the true first element of
>> the array. Not to mention most library functions use 0-numbering, so
>> you'd have to work around that as well.
>>
>> So, it can be done, but you're going against the grain of the language.
>
> I use fortran libraries, so that is not a problem for me. I only make
> the change once, while transferring the elements ... uhmm, make that
> twice.

Two opportunities to forget to lie about how big your array is :-)

> I wrote in my other post, 0 is weird to me, I have model of solution
> on paper ... if I keep 0 then all comes out different. And while
> comparing, I always get them mixed up. That's why I always try to
> adapt it to the paper situation.

Ever considered adapting the paper situation to it? You might find
that the results come out more naturally. Alternatively, idiomatic
Python seems to have a strong tendency not to need subscripting,
since you spend most of your time iterating through lists instead.

--
Rhodri James *-* Wildebeeste Herder to the Masses

Lada Kugis

unread,
Mar 31, 2009, 10:58:48 PM3/31/09
to
On Tue, 31 Mar 2009 19:30:15 -0700 (PDT), woo...@gmail.com wrote:

>Counting from zero through n-1 is used because it is the memory offset
>and not any kind of counter. Simplified, if you are iterating through
>a list, using a for loop or anything else, the first element/number is
>at memory offset zero because it is at the beginning. And if this is
>a list of 4 byte integers, the offset for the second element is 1*4
>bytes, etc. This idea, that somehow the first element of a list is
>the zero element is a fairly recent abnormality AFAIK. It perhaps
>comes from assumptions by people who are not familiar with what
>happens inside of a programming language, assuming incorrectly, that

I thoughts high level languages were created primarily so we don't
have to think about what happens inside a programming language, memory
offsets and the like.

>the (programming) world was created in their own image, and so
>programming languages were generated in the way that they think they
>were. This is a bad assumption for any programmer. Instead one
>should get in the habit of saying, in general as well as in this
>specific case, "This doesn't make sense. I wonder how __I__ screwed
>this up." Hopefully this will be helpful advice. Taking the attitude
>that you have screwed up yet again will get to the heart of the
>problem, and save many hours of frustration wondering why "this
>language/computer doesn't do what it is supposed to do".

Why do we try to create languages that are intuitive to humans, then ?

Lada

Brendon Wickham

unread,
Mar 31, 2009, 11:17:41 PM3/31/09
to Lada Kugis, pytho...@python.org
Since when should a machine (that's what a computer is after all), be
forced to contort itself into something that is capable of reflecting
the laws of physical matter?

Better perhaps to look at it from another angle - it's
counter-intuitive to think that the digital should mirror the
analogue. The digital can *virtualise* the real world, but it doesn't
do that by *working like* the real world.

It's not theory, it's actually what it is.


2009/4/1 Lada Kugis <lada....@gmail.com>:

> --
> http://mail.python.org/mailman/listinfo/python-list
>

Lada Kugis

unread,
Mar 31, 2009, 11:15:00 PM3/31/09
to
On Wed, 01 Apr 2009 03:59:36 +0100, "Rhodri James"
<rho...@wildebst.demon.co.uk> wrote:

>
>Two opportunities to forget to lie about how big your array is :-)

It is rank 3, meaning a33 is the last element. I don't see how any
alternative can be simpler than that.


>
>> I wrote in my other post, 0 is weird to me, I have model of solution
>> on paper ... if I keep 0 then all comes out different. And while
>> comparing, I always get them mixed up. That's why I always try to
>> adapt it to the paper situation.
>
>Ever considered adapting the paper situation to it?

And start mentally rewriting all the books on the subject - you must
be joking! The given one was a trivial example, used models are not
nearly that simple.

> You might find
>that the results come out more naturally.

... the force in the third node, at b(2) ?


Alternatively, idiomatic
>Python seems to have a strong tendency not to need subscripting,
>since you spend most of your time iterating through lists instead.

Yes, but you still need to give conditions, and for that you use
manually indexes. You need, for example, give force value at node 3,
which would come out as b(2).
Yes, there is a lot of iterating, but indexing is still important.

This loses some importance when you make a GUI, so you don't handle
all this manually, but I don't make (or know how to) those, so I'm
stuck with manual work ;-(

Still, tomorrow is a brand new day (rainy probably though).
I'm going to sleep, see you tomorrow.
Lada

Rhodri James

unread,
Mar 31, 2009, 11:44:31 PM3/31/09
to pytho...@python.org
On Wed, 01 Apr 2009 04:15:00 +0100, Lada Kugis <lada....@gmail.com>
wrote:

> On Wed, 01 Apr 2009 03:59:36 +0100, "Rhodri James"


> <rho...@wildebst.demon.co.uk> wrote:
>
>>
>> Two opportunities to forget to lie about how big your array is

> It is rank 3, meaning a33 is the last element. I don't see how any


> alternative can be simpler than that.

You were saying about translating between C programs and FORTRAN
libraries. C arrays are 0-based, FORTRANs are 1-based. The
entry and exit points therefore give you two opportunities to
forget that you need to translate. I don't rate that as simple,
myself.

Rhodri James

unread,
Mar 31, 2009, 11:39:26 PM3/31/09
to pytho...@python.org
On Wed, 01 Apr 2009 03:58:48 +0100, Lada Kugis <lada....@gmail.com>
wrote:

> I thoughts high level languages were created primarily so we don't


> have to think about what happens inside a programming language, memory
> offsets and the like.

Different programming languages were created for different purposes.
FORTRAN was built (and rebuilt, and rebuilt again) for crunching
numerical data, and there are only a limited number of ways that
"knowing what's going on under the hood" will help you write better
programs. C, on the other hand, was built for writing tools for
Unix. It gives you very little insulation from what's going on
inside, and knowing about that can be critical to the efficiency of
your programs.

> Why do we try to create languages that are intuitive to humans, then ?

To attempt to minimise the number of mistakes our intuition would
otherwise cause. Which rather begs the question of how varied intuition
is, and where that causes clashes we have to retreat to that unintuitive
beast, logic.

Dragging this back to the original topic, you clearly find starting
list indices from zero unintuitive. To me, with a mathematical
background, it's not just intuitive, it's correct. All sorts of
useful properties fall out from that, not the least of which is
the fact that "a[0:len(a)]" slices the whole of a list. You want the
first three items of a list? "a[:3]" will do nicely, sir. With
1-based indexing you start having to apply offsets in nonintuitive
ways more often than you might hope.

Steven D'Aprano

unread,
Mar 31, 2009, 11:54:34 PM3/31/09
to
On Wed, 01 Apr 2009 04:58:48 +0200, Lada Kugis wrote:

> Why do we try to create languages that are intuitive to humans, then ?

Because of the foolish hope that sufficiently easy syntax will make
excellent programmers out of average people.

Programming is not intuitive to humans. *Counting* isn't intuitive to
humans -- children need to learn how to count.

Very few things really are intuitive. Somebody once said that the only
truly intuitive thing is the nipple, but even with a broader definition
of intuitive, programming still isn't intuitive. There's nothing
intuitive about deleting a node from a red-black tree, or re-scaling a
floating point calculation to avoid overflow.

That's not to say that syntax doesn't matter. Poor syntax gets in the way
and makes it hard to read, comprehend and write code. But the aim of easy-
to-use syntax is for the syntax to get out of the way. Good syntax
doesn't turn a non-programmer into a programmer, but it lowers the
barrier to a non-programmer to learn how to program.


--
Steven

Hrvoje Niksic

unread,
Apr 1, 2009, 1:48:45 AM4/1/09
to
Chris Rebert <cl...@rebertia.com> writes:

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

And also that it is intuitive how to represent an empty slice
(foo[n:n]). When traversing over sublists, it's also a useful
property that foo[a:b] + foo[b:c] == foo.

Carl Banks

unread,
Apr 1, 2009, 3:40:17 AM4/1/09
to
On Mar 31, 7:23 pm, Lada Kugis <lada.ku...@gmail.com> wrote:
> On 01 Apr 2009 01:26:41 GMT, Steven D'Aprano
>
> <ste...@REMOVE.THIS.cybersource.com.au> wrote:
>
> >Why Python (and other languages) count from zero instead of one, and
> >why half-open intervals are better than closed intervals:
>
> >http://www.johndcook.com/blog/2008/06/26/why-computer-scientists-coun...

> >http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html
>
> steven, thanks for answering,
>
> yes, i saw the second one a little time ago (someone else posted it as
> well in really cute handwriting version :) and the first time just
> now, but the examples which both of them give don't seem to me to be
> that relevant, e.g. the pros don't overcome the cons.
>
> imho, although both sides (mathematical vs engineer) adress some
> points, none of them give the final decisive argument.
> i understand the math. point of view, but from the practical side it
> is not good. it goes nicely into his tidy theory of everything, but
> practical and intuitive it is not. as i said, being an engineer, i
> tend towards the other side,


Lada,

I am also an engineer, and I can tell your idea of intuitive is not
universal, even among engineers. I certainly do not lean toward one-
based indexing.

From a programming standpoint--and remember Python is a programming
language--zero-based indexing eliminates the need for a whole lot of
extra +1s and -1s when indexing, slicing, and iterating, a lot more
than it causes, and that is worth the "cost". This might not be
apparent to you if you never tried seriously taking advantage of
indexing from zero, or if your programming experience is very narrow.
These both seem to be true for you, so you'll just have to take my
word for it.

I'm sorry that the zero-based indexing isn't the most natural for your
field. There are some things about Python that aren't the natural
choice for me, too.

I would, however, highly recommend that you avoid the ridiculous
pseudo-one-based indexing trick you pulled when interfacing C to
Fortran. Python is zero-based, and you are going to have a much
better experience if you don't fight it. I assure you that it is
really not that hard to cope with indices being off by one from what
you have written down. Really. I have to interface two languages,
one of which indexes from one, the other from zero, and it really is
no problem.


Carl Banks

Diez B. Roggisch

unread,
Apr 1, 2009, 3:50:36 AM4/1/09
to
Lada Kugis schrieb:

> On 01 Apr 2009 01:26:41 GMT, Steven D'Aprano
> <ste...@REMOVE.THIS.cybersource.com.au> wrote:
>
>> Why Python (and other languages) count from zero instead of one, and
>> why half-open intervals are better than closed intervals:
>>
>> http://www.johndcook.com/blog/2008/06/26/why-computer-scientists-count-from-zero/
>> http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html
>
> steven, thanks for answering,
>
> yes, i saw the second one a little time ago (someone else posted it as
> well in really cute handwriting version :) and the first time just
> now, but the examples which both of them give don't seem to me to be
> that relevant, e.g. the pros don't overcome the cons.
>
> imho, although both sides (mathematical vs engineer) adress some
> points, none of them give the final decisive argument.
> i understand the math. point of view, but from the practical side it
> is not good. it goes nicely into his tidy theory of everything, but
> practical and intuitive it is not.

You keep throwing around the concept of "intuition" as if it were
something that existis in a globally fixed frame of reference. It is not.

From [1]:

"""
Klein found that under time pressure, high stakes, and changing
parameters, experts used their base of experience to identify similar
situations and intuitively choose feasible solutions.
"""

In other words: your gained *knowledge* (including mathematical
know-how) determines what's intuitive - to *you*.

So all arguing about intuition is rather irrelevant - to me, zero-based
counting is intuitive, and it is so with the same right as you prefer
one-based.

OTOH zero-based counting has technical reasons that also reduces the
amount of leaky abstraction problems [2], as it models the underlying
reality of memory locations + indexing.

Diez

[1] http://en.wikipedia.org/wiki/Intuition_(knowledge)
[2] http://www.joelonsoftware.com/articles/LeakyAbstractions.html

Steven D'Aprano

unread,
Apr 1, 2009, 4:06:28 AM4/1/09
to
On Wed, 01 Apr 2009 04:39:26 +0100, Rhodri James wrote:

> Dragging this back to the original topic, you clearly find starting list
> indices from zero unintuitive. To me, with a mathematical background,
> it's not just intuitive, it's correct. All sorts of useful properties
> fall out from that, not the least of which is the fact that
> "a[0:len(a)]" slices the whole of a list.

But some non-useful properties fall out of that too.

Want the fifth item? a[5] gives you the *sixth* item, which is weird, so
you have to use a[5-1] to get the fifth item.

There is a major clash between the names of ordinals in human languages
and zero-based counting. In human languages, the Nth-ordinal item comes
in position N. You can keep that useful convention with zero-based
counting by inventing the ugly word "zeroth", but that just leads to
bizarro-talk like "the zeroeth item comes first, the first item comes
second, and so on".

a[0:len(a)] is legal, a[0] is legal, but surprisingly a[len(a)] is an
error.

Despite coming from a Pascal background, I've come to appreciate and
prefer zero-based indexing for programming. But I'm not blind to the
disadvantages. I'll often work out an algorithm using pencil and paper
and counting from one, and then subtract one to get zero-based indexes.

There are advantages and disadvantages to both systems, but on balance, I
think that zero-based is a better system for programming, and one-based
for natural language.


--
Steven

andrew cooke

unread,
Apr 1, 2009, 7:04:12 AM4/1/09
to pytho...@python.org

something i don't think has been mentioned much - if you're using
"range()" in your python code then you're almost always doing it wrong.

i just grepped lepl and i use range 20 times in 9600 lines of code. out
of those, all but 3 are in "quick and dirty" tests or experimental code,
not in the main library itself (which is 6300 lines).

so in my main code, i use range() once in every 2000 lines of code,
approximately.

the three examples are:

(1) where i need to access two adjacent members of a list, and which has a
comment in the code explaining why it is not an error (in other words, i
was so unhappy with my code i needed to leave a note explaining why it was
like that)

(2) a use irrelevant to this discussion because i do not use the value to
an index an array.

(3) in the rather complex implementation of a circular buffer.

so in a small/moderate size library of 600 lines (including blanks and
comments, but excluding tests and exploratory code) the only time i have
used range with array indices i was either unhappy with the code, or
implementing a complex data structure.

andrew


andrew cooke

unread,
Apr 1, 2009, 7:05:46 AM4/1/09
to pytho...@python.org
andrew cooke wrote:
[...]

> so in a small/moderate size library of 600 lines (including blanks and
6000

Dave Angel

unread,
Apr 1, 2009, 7:06:27 AM4/1/09
to pythonlist
Natural language is full of ambiguity, which is why my parents used to
argue about the meaning of "next Wednesday," or of "the next exit."
Until you have a starting reference, and until you decide whether it's a
closed or open interval, you can't be sure everyone will get the same
semantics. Because of their bickering 50 years ago, I try to use a
longer phrase, such as "the Wednesday a week from today" or "exit 52."

In most? of Europe, the first floor is the one you get to after you go
up one flight of stairs. In the US, first floor is usually the ground
floor.

My ruler starts at zero, and has an explicit zero on it. Most rulers
start the same way, but don't actually show the zero. But if you had a
ruler that started with one, you'd end up with some off-by-one errors.

I repeatedly see people think that if Joe has $100, and Mary has three
times more, that she has $300. Yet these same people would balk at the
notion that 10% more would be $10.

English is a funny language (as I suspect most languages are), and full
of ambiguities and foolish inconsistencies. Having worked with some 35
languages over 35 years in the industry, I was glad that most of them
were zero based.

bearoph...@lycos.com

unread,
Apr 1, 2009, 7:39:39 AM4/1/09
to
Lada Kugis:

> (you have 1 apple, you start counting from 1 ...<

To little children I now show how to count starting from zero: apple
number zero, apple number one, etc, and they find it natural
enough :-)

Bye,
bearophile

Steven D'Aprano

unread,
Apr 1, 2009, 8:34:44 AM4/1/09
to


Ah, but that's not the same as counting ordinals from zero. Consider the
difference between an empty list, which has zero items, and a list of
length one, which as that item in position zero.

The empty list [] clearly has zero items, in zero "bins", so the bins
aren't numbered.

A list with one item [x] has one bin, labelled "Index 0".
A list with two items [x, y] has two bins, labelled Index 0 and Index 1.
A list with three items [x, y, z] has three bins, labelled Index 0, Index
1 and Index 2.
etc.

Counting "No apples plus one apple makes one apple" is easy enough. But
pointing to an apple clearly there and saying "Let's call that apple
number zero, even though there is one apple", that requires a very
special child!


--
Steven

Tim Rowe

unread,
Apr 1, 2009, 9:45:47 AM4/1/09
to pytho...@python.org
2009/4/1 Carl Banks <pavlove...@gmail.com>:

> I am also an engineer, and I can tell your idea of intuitive is not
> universal, even among engineers.  I certainly do not lean toward one-
> based indexing.

Another engineer here who finds 0-based indexing more intuitive than
1-based indexing.

--
Tim Rowe

Lou Pecora

unread,
Apr 1, 2009, 9:55:58 AM4/1/09
to
In article <1ej5t4930m29h0f6t...@4ax.com>,
Lada Kugis <lada....@gmail.com> wrote:

> On 01 Apr 2009 01:26:41 GMT, Steven D'Aprano
> <ste...@REMOVE.THIS.cybersource.com.au> wrote:
>
> >
> >Why Python (and other languages) count from zero instead of one, and
> >why half-open intervals are better than closed intervals:
> >
> >http://www.johndcook.com/blog/2008/06/26/why-computer-scientists-count-from-z
> >ero/
> >http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html
>
> steven, thanks for answering,
>
> yes, i saw the second one a little time ago (someone else posted it as
> well in really cute handwriting version :) and the first time just
> now, but the examples which both of them give don't seem to me to be
> that relevant, e.g. the pros don't overcome the cons.
>
> imho, although both sides (mathematical vs engineer) adress some
> points, none of them give the final decisive argument.
> i understand the math. point of view, but from the practical side it
> is not good. it goes nicely into his tidy theory of everything, but
> practical and intuitive it is not. as i said, being an engineer, i
> tend towards the other side, so this is biased opinion (nobody can be
> unbiased) but from a practical side it seems unpractical for
> engineering problems (and to me, the purpose of computers is to help
> humans to build a better world, not to prove theories - theories are
> useless if they don't help us in reality. so we should try to adapt
> computing to real world, not our world to computers).

There is nothing more practical than a good theory.
--- James Clerk Maxwell

You said you came from the C world (besides Fortran). If so, you have
already seen array indexing starting with 0 and going to n-1.

Why, then, should Python be so foreign to you?

--
-- Lou Pecora

Lou Pecora

unread,
Apr 1, 2009, 10:09:24 AM4/1/09
to
In article <72i5t4tgfo2h4gd6g...@4ax.com>,
Lada Kugis <lada....@gmail.com> wrote:


> and
> the (m-n) point Chris was trying to explain doesn't seem that relevant
> to me.

That's because you haven't done enough programming really using the
Python structures and objects. You can really do a lot with lists and
tuples. When you do you will see Chris' point emphatically.

--
-- Lou Pecora

Lada Kugis

unread,
Apr 1, 2009, 10:08:44 AM4/1/09
to
On Wed, 1 Apr 2009 00:40:17 -0700 (PDT), Carl Banks
<pavlove...@gmail.com> wrote:

>
>Lada,
>
>I am also an engineer, and I can tell your idea of intuitive is not
>universal, even among engineers. I certainly do not lean toward one-
>based indexing.
>
>From a programming standpoint--and remember Python is a programming
>language--zero-based indexing eliminates the need for a whole lot of
>extra +1s and -1s when indexing, slicing, and iterating, a lot more
>than it causes, and that is worth the "cost". This might not be
>apparent to you if you never tried seriously taking advantage of
>indexing from zero, or if your programming experience is very narrow.
>These both seem to be true for you, so you'll just have to take my
>word for it.


You have repeated several cs based points already stated. But apart
from a programming standpoint - could you give a few examples, where
"on paper" (as to avoid stepping into "programmer's territory") zero
indexing could be more intuitive ?
(of course, taking into account your previous based calculations,
which are based on 1 indexing - I imagine you still use matrices with
a11 as a first element)

Lada

Lada Kugis

unread,
Apr 1, 2009, 10:12:27 AM4/1/09
to
On 01 Apr 2009 08:06:28 GMT, Steven D'Aprano
<ste...@REMOVE.THIS.cybersource.com.au> wrote:

>
>There are advantages and disadvantages to both systems, but on balance, I
>think that zero-based is a better system for programming, and one-based
>for natural language.

Nicely put.

Yes, along with some of your other arguments, I think I can agree that
this sums it up best. I'll just have to adapt myself to natural
language thinking at one side, and programming thinking at the other.

Lada

MRAB

unread,
Apr 1, 2009, 10:45:55 AM4/1/09
to pytho...@python.org
Lada Kugis wrote:
[snip]
> Yes, that's it. I won't argue over it, since I can't change it, but 1
> is still more natural to me (it is "the real world" way). The above
> pros seem to me to be very little compared to the cons of the ... and

> the (m-n) point Chris was trying to explain doesn't seem that relevant
> to me.
> I always thought since python is trying so hard to be as intuitive as
> it can get it would be the other way (you have 1 apple, you start
> counting from 1 ...
>
[snip]
But you might not have any apples, so you should start from 0! :-)

MRAB

unread,
Apr 1, 2009, 10:47:15 AM4/1/09
to pytho...@python.org
Steven D'Aprano wrote:
> On Wed, 01 Apr 2009 04:58:48 +0200, Lada Kugis wrote:
>
>> Why do we try to create languages that are intuitive to humans, then ?
>
> Because of the foolish hope that sufficiently easy syntax will make
> excellent programmers out of average people.
>
> Programming is not intuitive to humans. *Counting* isn't intuitive to
> humans -- children need to learn how to count.
>
[snip]
Research suggests that your wrong. For example, even baby chicks can
count:

http://news.bbc.co.uk/1/hi/sci/tech/7975260.stm

andrew cooke

unread,
Apr 1, 2009, 11:10:40 AM4/1/09
to MRAB, pytho...@python.org
MRAB wrote:

> Steven D'Aprano wrote:
>> On Wed, 01 Apr 2009 04:58:48 +0200, Lada Kugis wrote:
>>
>>> Why do we try to create languages that are intuitive to humans, then ?
>>
>> Because of the foolish hope that sufficiently easy syntax will make
>> excellent programmers out of average people.
>>
>> Programming is not intuitive to humans. *Counting* isn't intuitive to
>> humans -- children need to learn how to count.
>>
> [snip]
> Research suggests that your wrong. For example, even baby chicks can
> count:
>
> http://news.bbc.co.uk/1/hi/sci/tech/7975260.stm

i saw that earlier today. it's really pushing the definition of "count",
at least as described there.

there have been similar experiments where they address whether the animal
is actually looking at "how big" the total "pile" is rather than counting
(do they know the difference between two small things and one big thing,
for example). that experiment doesn't seem to address this.

andrew


Carl Banks

unread,
Apr 1, 2009, 1:05:36 PM4/1/09
to
On Apr 1, 7:08 am, Lada Kugis <lada.ku...@gmail.com> wrote:
> On Wed, 1 Apr 2009 00:40:17 -0700 (PDT), Carl Banks
>
>
>
>
>
> <pavlovevide...@gmail.com> wrote:
>
> >Lada,
>
> >I am also an engineer, and I can tell your idea of intuitive is not
> >universal, even among engineers.  I certainly do not lean toward one-
> >based indexing.
>
> >From a programming standpoint--and remember Python is a programming
> >language--zero-based indexing eliminates the need for a whole lot of
> >extra +1s and -1s when indexing, slicing, and iterating, a lot more
> >than it causes, and that is worth the "cost".  This might not be
> >apparent to you if you never tried seriously taking advantage of
> >indexing from zero, or if your programming experience is very narrow.
> >These both seem to be true for you, so you'll just have to take my
> >word for it.
>
> You have repeated several cs based points already stated. But apart
> from a programming standpoint - could you give a few examples, where
> "on paper" (as to avoid stepping into "programmer's territory") zero
> indexing could be more intuitive ?

That's beside the point. Python's job is to be usable as a
programming language. It made a decision to use zero-based indexing
so as to simplify programming usage. Therefore, that's what you have
to use for matrix indices, whether it is intuitive for you or not.

I have no real opinion whether zero- or one-based indexing works best
on paper for engineering calculations, except that it's a trivial
consideration.

> (of course, taking into account your previous based calculations,
> which are based on 1 indexing - I imagine you still use matrices with
> a11 as a first element)

I don't know what you're referring to by my previous based
calculations, and the sentences doesn't make sense, so I can't answer
this.

FTR: I use zero-based matrix indices when I'm using a language with
zero-based indexing, and one-based indices when using a language with
one-based indexing. Simple as that. You should do the same.


Carl Banks

MRAB

unread,
Apr 1, 2009, 1:08:45 PM4/1/09
to pytho...@python.org
andrew cooke wrote:
> MRAB wrote:
>> Steven D'Aprano wrote:
>>> On Wed, 01 Apr 2009 04:58:48 +0200, Lada Kugis wrote:
>>>
>>>> Why do we try to create languages that are intuitive to humans, then ?
>>> Because of the foolish hope that sufficiently easy syntax will make
>>> excellent programmers out of average people.
>>>
>>> Programming is not intuitive to humans. *Counting* isn't intuitive to
>>> humans -- children need to learn how to count.
>>>
>> [snip]
>> Research suggests that your wrong. For example, even baby chicks can
>> count:
>>
>> http://news.bbc.co.uk/1/hi/sci/tech/7975260.stm
>
> i saw that earlier today. it's really pushing the definition of "count",
> at least as described there.
>
> there have been similar experiments where they address whether the animal
> is actually looking at "how big" the total "pile" is rather than counting
> (do they know the difference between two small things and one big thing,
> for example). that experiment doesn't seem to address this.
>
Just occurred to me. Chicks and eggs, on 1 April, with Easter
approaching. Hmm...

Mensanator

unread,
Apr 1, 2009, 1:47:27 PM4/1/09
to
On Apr 1, 9:08 am, Lada Kugis <lada.ku...@gmail.com> wrote:
> On Wed, 1 Apr 2009 00:40:17 -0700 (PDT), Carl Banks
>
>
>
>
>
> <pavlovevide...@gmail.com> wrote:
>
> >Lada,
>
> >I am also an engineer, and I can tell your idea of intuitive is not
> >universal, even among engineers.  I certainly do not lean toward one-
> >based indexing.
>
> >From a programming standpoint--and remember Python is a programming
> >language--zero-based indexing eliminates the need for a whole lot of
> >extra +1s and -1s when indexing, slicing, and iterating, a lot more
> >than it causes, and that is worth the "cost".  This might not be
> >apparent to you if you never tried seriously taking advantage of
> >indexing from zero, or if your programming experience is very narrow.
> >These both seem to be true for you, so you'll just have to take my
> >word for it.
>
> You have repeated several cs based points already stated. But apart
> from a programming standpoint - could you give a few examples, where
> "on paper" (as to avoid stepping into "programmer's territory") zero
> indexing could be more intuitive ?

Here's an easy example: Standard Positional Number Systems.

765 in octal is

7 * 8**2 +
6 * 8**1 +
5 * 8**0

123 in decimal is

1 * 10**2 +
2 * 10**1 +
3 * 10**0

666 in hexadecimal is

6 * 16**2 +
6 * 16**1 +
6 * 16**0

0-based indexing is kinda important.

> (of course, taking into account your previous based calculations,
> which are based on 1 indexing - I imagine you still use matrices with
> a11 as a first element)
>

> Lada- Hide quoted text -
>
> - Show quoted text -

Lou Pecora

unread,
Apr 1, 2009, 2:14:47 PM4/1/09
to
In article <91t6t4hfjicgvdrcg...@4ax.com>,
Lada Kugis <lada....@gmail.com> wrote:

> On Wed, 1 Apr 2009 00:40:17 -0700 (PDT), Carl Banks
> <pavlove...@gmail.com> wrote:
>
> >
> >Lada,
> >
> >I am also an engineer, and I can tell your idea of intuitive is not
> >universal, even among engineers. I certainly do not lean toward one-
> >based indexing.
> >
> >From a programming standpoint--and remember Python is a programming
> >language--zero-based indexing eliminates the need for a whole lot of
> >extra +1s and -1s when indexing, slicing, and iterating, a lot more
> >than it causes, and that is worth the "cost". This might not be
> >apparent to you if you never tried seriously taking advantage of
> >indexing from zero, or if your programming experience is very narrow.
> >These both seem to be true for you, so you'll just have to take my
> >word for it.
>
>
> You have repeated several cs based points already stated. But apart
> from a programming standpoint - could you give a few examples, where
> "on paper" (as to avoid stepping into "programmer's territory") zero
> indexing could be more intuitive ?

This has become a moving target. I thought your original complaint was
about Python (the programming language) vs. Fortran (the programming
language) and C (the programming language used in an odd way).

--
-- Lou Pecora

Arnaud Delobelle

unread,
Apr 1, 2009, 5:32:37 PM4/1/09
to
Lada Kugis <lada....@gmail.com> writes:

> I'm coming from fortran and c background so I'm certainly biased by
> them. But if you could explain one thing to me:
>
> in fortran for example:
> for i=1,n
> goes from 1,2,3,4,...,n
>
> 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)
>
> Why is that so ? What were the reasons for that "not including" part ?
> It troubles me greatly, and I cannot see it's advantages over the
> "standard" "up to and including" n.
>
> Best regards
> Lada

Luckily Python allows you to create your own indexing on lists:

def dec(i):
if isinstance(i, slice):
return slice(dec(i.start), dec(i.stop), i.step)
elif i is None or i < 0:
return i
else:
return i - 1

defop = """
def __%sitem__(s,i,*r):
val = list.__%sitem__(s,dec(i),*r)
if isinstance(i, slice): val = List1(val)
return val
def __%sslice__(s,i,j,*r):
return List1(list.__%sslice__(s,dec(i),dec(j),*r))
"""

class List1(list):
for op in 'del', 'get', 'set':
exec defop % (op, op, op, op)
def index(self, x):
return list.index(self, x) + 1
def insert(self, i, x):
list.insert(self, dec(i), x)
def pop(self, i=None):
return list.pop() if i is None else list.pop(dec(i))
for op in 'add', 'mul', 'radd', 'rmul':
exec "def __%s__(*r): return List1(list.__%s__(*r))" % (op, op)

l1 = List1(range(10))
l2 = List1("Python rules")


I'll let you play with l1 and l2.

--
Arnaud

PS. What day is it again?

Carl Banks

unread,
Apr 1, 2009, 6:35:36 PM4/1/09
to
On Apr 1, 2:32 pm, Arnaud Delobelle <arno...@googlemail.com> wrote:

If I were your boss and you ever pulled something like this, your ass
would be so fired.

This is unforgiveable, not only changing the indexing semantics of
Python (because a user would have NO CLUE that something underlying
has been changed, and thus it should never be done), but also for the
needless abuse of exec.


Carl Banks

Rhodri James

unread,
Apr 1, 2009, 7:17:18 PM4/1/09
to pytho...@python.org
On Wed, 01 Apr 2009 15:12:27 +0100, Lada Kugis <lada....@gmail.com>
wrote:

> On 01 Apr 2009 08:06:28 GMT, Steven D'Aprano

I always think it's sad that the concept of "zero" arrived too late to
influence our fundamentally latinate language for ordinal numbers. (In
other words, don't go thinking that there's anything logical about
natural language :-)

John O'Hagan

unread,
Apr 2, 2009, 12:23:32 AM4/2/09
to pytho...@python.org
On Wed, 1 Apr 2009, Steven D'Aprano wrote:
> On Wed, 01 Apr 2009 04:39:26 +0100, Rhodri James wrote:
> > Dragging this back to the original topic, you clearly find starting list
> > indices from zero unintuitive. To me, with a mathematical background,
> > it's not just intuitive, it's correct. All sorts of useful properties
> > fall out from that, not the least of which is the fact that
> > "a[0:len(a)]" slices the whole of a list.
>
> But some non-useful properties fall out of that too.
>
> Want the fifth item? a[5] gives you the *sixth* item, which is weird, so
> you have to use a[5-1] to get the fifth item.
>
> There is a major clash between the names of ordinals in human languages
> and zero-based counting. In human languages, the Nth-ordinal item comes
> in position N. You can keep that useful convention with zero-based
> counting by inventing the ugly word "zeroth", but that just leads to
> bizarro-talk like "the zeroeth item comes first, the first item comes
> second, and so on".
>
> a[0:len(a)] is legal, a[0] is legal, but surprisingly a[len(a)] is an
> error.
>
> Despite coming from a Pascal background, I've come to appreciate and
> prefer zero-based indexing for programming. But I'm not blind to the
> disadvantages. I'll often work out an algorithm using pencil and paper
> and counting from one, and then subtract one to get zero-based indexes.

[...]

Despite being thoroughly acclimatised to zero-based indexing and having no
wish to change it, I'm starting to see the OP's point.

Many of the arguments presented in this thread in favour of zero-based
indexing have rather been arguments for half-open intervals, which I don't
think are in dispute. We all want these to be true:

foo[:n] is the first n items of the sequence foo
foo[:n] + foo[n:] == foo
len(foo[n:m]) == m-n
(foo[n:n]) is an empty sequence
etc.

and they are true with 0-based indexing if we exclude the last number, or
equally with 1-based indexing if we exclude the first.

In a way, Python already has 1-based indexing, in terms of absolute index
values when counting backwards: the last element of a sequence is indexed -1,
the second-last -2, etc., so that the first element is foo[-len(foo)].

1-based indexing mirrors this so that foo[len(foo)] is not a surprising error
as Steven mentions above, but the last element of foo.

Also the other weirdness Steven mentioned goes away: the nth element of foo
becomes foo[n], and the OP's issue with an extant element having an
ordinality of 0 ("zeroeth") also goes away, i.e. ordinality and cardinality
are lined up.

Beyond being part of a conventionally-ordered set of keys, what can an
ordinality of zero actually mean? (That's a sincere question.)

But as long as we need to both count items and measure intervals, we have to
deal with these +/-1 adjustments in any case.

As an aside, a similar issue arises in music theory, in which intervals are
traditionally expressed relative to scale degrees starting from one (counting
the notes), or in more modern language, in semitones starting from zero
(measuring the interval). This gives rise to similar (minor and short-lived)
confusions.

+/-1 :)

Regards,

John

Lie

unread,
Apr 2, 2009, 12:58:47 AM4/2/09
to
On Apr 1, 7:06 pm, Steven D'Aprano
<ste...@REMOVE.THIS.cybersource.com.au> wrote:

> There is a major clash between the names of ordinals in human languages
> and zero-based counting. In human languages, the Nth-ordinal item comes
> in position N. You can keep that useful convention with zero-based
> counting by inventing the ugly word "zeroth", but that just leads to
> bizarro-talk like "the zeroeth item comes first, the first item comes
> second, and so on".

No, there won't be any bizarro-talk. There is no argument: the zeroeth
item comes zeroeth, the first item comes first, and so on. The index
for the very zeroeth thing in a list is 0, so to get the zeroeth item
you use s[0]. While to get the first item you use s[1]. It's very
intuitive, isn't it?

Aaron Brady

unread,
Apr 2, 2009, 1:05:20 AM4/2/09
to

Robot 1: I won zeroeth place at the contest, honey!
Robot 2: Congratulations! I knew you could do it.

Lie

unread,
Apr 2, 2009, 2:27:04 AM4/2/09
to

That should be Robot 0 and Robot 1.

Steven D'Aprano

unread,
Apr 2, 2009, 2:28:49 AM4/2/09
to
On Thu, 02 Apr 2009 04:23:32 +0000, John O'Hagan wrote:

> Beyond being part of a conventionally-ordered set of keys, what can an
> ordinality of zero actually mean? (That's a sincere question.)

In set theory, you start by defining the integers like this:

0 is the cardinality (size) of the empty set, the set with nothing in it.

1 is the cardinality of the set of empty sets, that is, the set
containing nothing but the empty set.

2 is the cardinality of the set of the empty set plus the set of empty
sets.

3 is the cardinality of the set containing the empty set, plus the set of
empty sets, plus the set of (the empty set plus the set of empty sets).

And so forth, to infinity and beyond.

Or to put it another way:


0 = len( {} )
1 = len( {{}} )
2 = len( {{}, {{}}} )
3 = len( {{}, {{}}, {{}, {{}}} )
etc.

For non-infinite sets, you can treat ordinal numbers and cardinal numbers
as more or less identical. So an ordinality of zero just means the number
of elements of something that doesn't exist.

How that relates to whether indexing should start at one or zero, I have
no idea.

Oh, and speaking of... I'm shocked, SHOCKED I say, that nobody has given
that quote about the compromise of 0.5.


--
Steven

Steven D'Aprano

unread,
Apr 2, 2009, 2:29:49 AM4/2/09
to

No, because "first", "second", "third" etc. have existed in the English
language for hundreds of years and everybody knows them. "Zeroeth" was
probably invented a few decades ago, and is known by maybe 1% of the
English-speaking population.

Given the list [a, b, c], if you ask even a C programmer *in English*
"what's the first item?", they will almost invariably answer a rather
than b.


--
Steven

Carl Banks

unread,
Apr 2, 2009, 2:47:00 AM4/2/09
to
On Apr 1, 9:23 pm, John O'Hagan <resea...@johnohagan.com> wrote:
> Despite being thoroughly acclimatised to zero-based indexing and having no
> wish to change it, I'm starting to see the OP's point.
>
> Many of the arguments presented in this thread in favour of zero-based
> indexing have rather been arguments for half-open intervals, which I don't
> think are in dispute. We all want these to be true:
>
> foo[:n] is the first n items of the sequence foo
> foo[:n] + foo[n:] == foo
> len(foo[n:m]) == m-n
> (foo[n:n]) is an empty sequence
> etc.
>
> and they are true with 0-based indexing if we exclude the last number, or
> equally with 1-based indexing if we exclude the first.

Unless I'm missing something, wouldn't that mean:

range(0,10) -> [1,2,3,4,5,6,7,8,9,10]

Even though it's theoretically just another way to line up the open
interval, as practical matter it's going to be a lot more confusing.
Of course you could exclude the last number with one-based indexing
also, but that would be confusing too, since you would have to use
something like range(1,len(x)+1) to iterate over the items of x.

Given that, I'm going to disagree that a half-open interval is
desirable in the case of one-based indexing.

Furthermore, I know of no languages that use both one-based indexing
and half-open intervals. Do you know of any?


> Beyond being part of a conventionally-ordered set of keys, what can an
> ordinality of zero actually mean? (That's a sincere question.)

I think people were being facetious. To me the first item in the list
is x[0]--ordinal does not match cardinal. However, I don't use
ordinals much when talking about list items; I'll say item 2, not
third item.


Carl Banks

Aaron Brady

unread,
Apr 2, 2009, 2:47:13 AM4/2/09
to
On Apr 2, 1:29 am, Steven D'Aprano

However, if you ask him/er, "What is the item that is 0 items from the
start of the list?", what will s/he say?

Hrvoje Niksic

unread,
Apr 2, 2009, 2:28:19 AM4/2/09
to
Carl Banks <pavlove...@gmail.com> writes:

> This is unforgiveable, not only changing the indexing semantics of
> Python (because a user would have NO CLUE that something underlying
> has been changed, and thus it should never be done), but also for
> the needless abuse of exec.

Then I guess you'd fire Guido, too -- from socket.py:

class _socketobject(object):
[...]
_s = ("def %s(self, *args): return self._sock.%s(*args)\n\n"
"%s.__doc__ = _realsocket.%s.__doc__\n")
for _m in _socketmethods:
exec _s % (_m, _m, _m, _m)
del _m, _s

Arnaud Delobelle

unread,
Apr 2, 2009, 3:23:36 AM4/2/09
to
Carl Banks wrote:

> On Apr 1, 2:32 pm, Arnaud Delobelle <arno...@googlemail.com> wrote:

Check the date on the line above (and the PS in that post).

>
> If I were your boss and you ever pulled something like this, your ass
> would be so fired.
>
> This is unforgiveable, not only changing the indexing semantics of
> Python (because a user would have NO CLUE that something underlying
> has been changed, and thus it should never be done), but also for the
> needless abuse of exec.

Gotcha ;)

--
Arnaud

PS. I disagree about the 'needless abuse of exec'.

Carl Banks

unread,
Apr 2, 2009, 4:02:16 AM4/2/09
to
On Apr 1, 11:28 pm, Hrvoje Niksic <hnik...@xemacs.org> wrote:

Damn straight I would, recklessly using exec like he owns the language
or something.


Carl Bansk

John O'Hagan

unread,
Apr 2, 2009, 4:09:16 AM4/2/09
to pytho...@python.org
On Thu, 2 Apr 2009, Steven D'Aprano wrote:
> On Thu, 02 Apr 2009 04:23:32 +0000, John O'Hagan wrote:
> > Beyond being part of a conventionally-ordered set of keys, what can an
> > ordinality of zero actually mean? (That's a sincere question.)
>

[snip erudite definition of cardinality]

> For non-infinite sets, you can treat ordinal numbers and cardinal numbers
> as more or less identical. So an ordinality of zero just means the number
> of elements of something that doesn't exist.

This is the bit I don't get - I had thought of ordinality as something
attached to each item - ['a','b','c'] has a cardinality of 3, and elements of
ordinality 1, 2 and 3 (first,second, third) respectively. So it's possible to
have a cardinality of zero (an empty sequence does) but only "something that
doesn't exist" can have an ordinality of zero; as soon as there is an item,
its ordinality is 1. Shoot me down, please!

> How that relates to whether indexing should start at one or zero, I have
> no idea.

Only insofar as the "weirdness" of indexing being out of step with
ordinality/cardinality matters, i.e. not that much. :)

John

Arnaud Delobelle

unread,
Apr 2, 2009, 4:36:25 AM4/2/09
to
Steven D'Aprano wrote:

> In set theory, you start by defining the integers like this:
>
> 0 is the cardinality (size) of the empty set, the set with nothing in it.
>
> 1 is the cardinality of the set of empty sets, that is, the set
> containing nothing but the empty set.
>
> 2 is the cardinality of the set of the empty set plus the set of empty
> sets.
>
> 3 is the cardinality of the set containing the empty set, plus the set of
> empty sets, plus the set of (the empty set plus the set of empty sets).
>
> And so forth, to infinity and beyond.
>
> Or to put it another way:
>
>
> 0 = len( {} )
> 1 = len( {{}} )
> 2 = len( {{}, {{}}} )
> 3 = len( {{}, {{}}, {{}, {{}}} )

FWIW this is the way I learnt it AFAIK:

Ordinals
=======

0 *is* the empty set
1 *is* the the the singleton composed of the empty set, i.e. {0}
2 *is* the set {0, 1}
3 *is* the set {0, 1, 2}
...
n + 1 := n U {n}

It's nice because:
* the interval [0, n) is just the number n
* n < m iff n is a subset of m iff n is a member of m

Cardinals
=========

A cardinal is an equivalence class under the equivalence relation S ~
S' iff there is a bijection between S and S'. Obviously, finite
cardinals contain only one ordinal so finite cardinals can be
identified with their ordinal representative.

--
Arnaud

Gabriel Genellina

unread,
Apr 2, 2009, 5:59:55 AM4/2/09
to pytho...@python.org
En Wed, 01 Apr 2009 08:04:12 -0300, andrew cooke <and...@acooke.org>
escribió:

> something i don't think has been mentioned much - if you're using
> "range()" in your python code then you're almost always doing it wrong.
>
> i just grepped lepl and i use range 20 times in 9600 lines of code. out
> of those, all but 3 are in "quick and dirty" tests or experimental code,
> not in the main library itself (which is 6300 lines).
>
> (1) where i need to access two adjacent members of a list, and which has
> a
> comment in the code explaining why it is not an error (in other words, i
> was so unhappy with my code i needed to leave a note explaining why it
> was
> like that)

From your description I guess this "range" usage could have been avoided,
using enumerate instead. A silly example:

for i,elem in enumerate(some_list):
if i>0:
prev = some_list[i-1]
print (elem+prev)/2

instead of:

for i in range(1, len(some_list)):
elem = some_list[i]
prev = some_list[i-1]
print ...

> (2) a use irrelevant to this discussion because i do not use the value to
> an index an array.
>
> (3) in the rather complex implementation of a circular buffer.

I can't tell, but perhaps enumerate() could have been used here too?

> so in a small/moderate size library of 6000 lines (including blanks and
> comments, but excluding tests and exploratory code) the only time i have
> used range with array indices i was either unhappy with the code, or
> implementing a complex data structure.

Maybe the ratio is even less than that.

--
Gabriel Genellina

Lou Pecora

unread,
Apr 2, 2009, 12:44:38 PM4/2/09
to
In article <pan.2009.04...@REMOVE.THIS.cybersource.com.au>,

Steven D'Aprano <ste...@REMOVE.THIS.cybersource.com.au> wrote:

> So an ordinality of zero just means the number
> of elements of something that doesn't exist.


You do realize that will give most people headaches. :-)

--
-- Lou Pecora

Tim Wintle

unread,
Apr 2, 2009, 1:35:01 PM4/2/09
to pytho...@python.org
On Thu, 2009-04-02 at 06:28 +0000, Steven D'Aprano wrote:
> In set theory, you start by defining the integers like this:
<snip>

>
> 0 = len( {} )
> 1 = len( {{}} )
> 2 = len( {{}, {{}}} )
> 3 = len( {{}, {{}}, {{}, {{}}} )
> etc.
not quite len() - surely you mean something like "any object along with
an algebra in which the left hand side is equivalent to the right in the
algebra of set theory?" - at least for ordinals.

The cardinal is then (for finite numbers) the length of that.


Or, in a pythonic sense (taking 0,1,2,... to be variable names):
0 = set()
1 = set(0)
2 = set(1,0)
3 = set(2,1,0)
3 = set(3,2,1,0)
etc.


> How that relates to whether indexing should start at one or zero, I
> have
> no idea.

so in this sense, range(n) is actually very close to the ordinal value
of 0 (except for being a list and not a set - but it's not in 3.0)

i.e. range(n) returns something very similar to the ordinal "n", and
with cardinality n. That seems very sensible to me.


> Oh, and speaking of... I'm shocked, SHOCKED I say, that nobody has
> given that quote about the compromise of 0.5.

"God made the integers, all else is the work of man" - Leopold Kronecker

...holding myself back from complaining about integer division in Py3K
when the philosophical question of whether irrational numbers even exist
(in a physics sense) is fairly open.

Tim W


Lou Pecora

unread,
Apr 2, 2009, 5:29:58 PM4/2/09
to
In article
<bd70785c-1e86-4437...@k19g2000prh.googlegroups.com>,
Carl Banks <pavlove...@gmail.com> wrote:


>
> I think people were being facetious. To me the first item in the list
> is x[0]--ordinal does not match cardinal. However, I don't use
> ordinals much when talking about list items; I'll say item 2, not
> third item.


Well, it's been said in many forms in this thread, but maybe this
version will click with some. Thinking of ordinals as specifying
position by order and cardinals as counting the number of steps from a
specified place to an item you just have to realize that 0 and 1 based
indexing have decided to use *different* definitions for the
conglomerate symbols A[i] or A(i):

1 based indexing (ordinality):
A[i] is the ith item in the ordered list (1st, 2nd, etc. - no need for
0th as an ordinal)

0 based indexing (cardinality):
A[i] is the item i steps from the beginning of the list.

I know most of what's been said is all around the above, I just thought
explict statements might help. Both are prefectly reasonable and
consistent definitions. Confusion only comes when you try to force the
defintion of one of them on the other and then say it's illogical or not
natural. Both are natural.

Of course, in some languages like C an array name, say A, points to the
first item in memory of the array which is assumed to be structured
sequentially. Then A[0] is the first item at the address A or since we
are using cardinality (0 based indexing) it's the item 0 steps from the
beginning. A[1] is the item at address A+1, i.e. 1 step from the
address A, the array beginning.

I suspect that was a very practical choice for C since it's a systems
language and down at that level you're flipping bit, bytes, addresses,
etc. But a practical consequence was that there was very little +1 or
-1 arithmetic necessary to manipulate the array elements. That carried
over into other languages and their design. People have already pointed
out the nice features of such in Python where A[n:n] is an empty list,
A[:n]+A[n:]=A, etc.

Now, I'm not a systems/computer guy. Just a scientist who does a lot of
number crunching. But I have found out that even in that case you end
of traversing lists, tuples, etc. a lot. Slicing and dicing them. And
you quickly come to appreciate the 0 based approach to indexing and soon
don't miss the Fortran 1-based indexing.

--
-- Lou Pecora

Emile van Sebille

unread,
Apr 2, 2009, 6:16:57 PM4/2/09
to pytho...@python.org
Lou Pecora wrote:
> Confusion only comes when you try to force the
> defintion of one of them on the other and then say it's illogical or not
> natural. Both are natural.

Consider the French 'Premiere etage' vs the American 'First Floor'

Emile

Tim Wintle

unread,
Apr 2, 2009, 7:34:37 PM4/2/09
to pytho...@python.org
On Thu, 2009-04-02 at 15:16 -0700, Emile van Sebille wrote:

> Lou Pecora wrote:
> > Confusion only comes when you try to force the
> > defintion of one of them on the other and then say it's illogical or not
> > natural. Both are natural.
>
> Consider the French 'Premiere etage' vs the American 'First Floor'

or even in the same language - "first floor" in English (UK) is very
different from "first floor" in English (US).

>
> Emile
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list

Aaron Brady

unread,
Apr 2, 2009, 11:21:47 PM4/2/09
to
On Apr 2, 6:34 pm, Tim Wintle <tim.win...@teamrubber.com> wrote:
> On Thu, 2009-04-02 at 15:16 -0700, Emile van Sebille wrote:
> > Lou Pecora wrote:
> > > Confusion only comes when you try to force the
> > > defintion of one of them on the other and then say it's illogical or not
> > > natural.  Both are natural.
>
> > Consider the French 'Premiere etage' vs the American 'First Floor'
>
> or even in the same language - "first floor" in English (UK) is very
> different from "first floor" in English (US).

Did I tell you guys that 'natural' has 38 definitions at
dictionary.com?

Lie

unread,
Apr 3, 2009, 2:46:57 AM4/3/09
to
On Apr 2, 5:29 pm, Steven D'Aprano

Alternatively:
"One friend of mine half-seriously advanced the following thesis: We
should count from zero. But "first" is, etymologically, a diminution
of "foremost", and (as TomStambaugh says) should mean "0th" when we
count from 0. And "second" is from the Latin "secundus", meaning
"following", so it should mean "1th" when we count from 0. Obviously
the ordinals from "third" onwards get their names from the numbers.
So... we need a new word for "2th". He proposed "twifth". Thus: first,
second, twifth, third, fourth, ..."
-- GarethMcCaughan (from http://c2.com/cgi/wiki?ZeroAndOneBasedIndexes
)

No zeroeth, "twifth"

Lou Pecora

unread,
Apr 3, 2009, 8:36:17 AM4/3/09
to
In article
<5c92e9bd-1fb4-4c01...@e21g2000yqb.googlegroups.com>,
Aaron Brady <casti...@gmail.com> wrote:


Amazing. I suggest you pick the one that fits best.

--
-- Lou Pecora

MRAB

unread,
Apr 3, 2009, 9:27:28 AM4/3/09
to pytho...@python.org
Lie wrote:
[snip]

> Alternatively:
> "One friend of mine half-seriously advanced the following thesis: We
> should count from zero. But "first" is, etymologically, a diminution
> of "foremost", and (as TomStambaugh says) should mean "0th" when we
> count from 0. And "second" is from the Latin "secundus", meaning
> "following", so it should mean "1th" when we count from 0. Obviously
> the ordinals from "third" onwards get their names from the numbers.
> So... we need a new word for "2th". He proposed "twifth". Thus: first,
> second, twifth, third, fourth, ..."
>
I propose "twoth" (sounds like "tooth"). :-)

alex23

unread,
Apr 3, 2009, 11:43:35 AM4/3/09
to
On Apr 3, 10:36 pm, Lou Pecora <pec...@anvil.nrl.navy.mil> wrote:

>  Aaron Brady <castiro...@gmail.com> wrote:
> > Did I tell you guys that 'natural' has 38 definitions at
> > dictionary.com?
>
> Amazing.  I suggest you pick the one that fits best.

You mean the one that feels most natural?

Aaron Brady

unread,
Apr 3, 2009, 12:59:15 PM4/3/09
to

No, not feels. *Is*.

Aahz

unread,
Apr 7, 2009, 1:45:36 PM4/7/09
to
In article <pecora-D381E9....@ra.nrl.navy.mil>,

"The wonderful thing about standards is that there are so many to choose
from."
--
Aahz (aa...@pythoncraft.com) <*> http://www.pythoncraft.com/

"...string iteration isn't about treating strings as sequences of strings,
it's about treating strings as sequences of characters. The fact that
characters are also strings is the reason we have problems, but characters
are strings for other good reasons." --Aahz

Chris Nash

unread,
Jul 10, 2013, 12:43:15 PM7/10/13
to pytho...@python.org
The first item in a sequence is at index zero because it is that far away from
the beginning. The second item is one away from the beginning. That is the
reason for zero-based indexing.

0 new messages