python for loop
Lou Pecora
pecora at anvil.nrl.navy.mil
Thu Apr 2 23:29:58 CEST 2009
In article
<bd70785c-1e86-4437-a14e-d84028f57961 at k19g2000prh.googlegroups.com>,
Carl Banks <pavlovevidence at 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
More information about the Python-list
mailing list