Re:Why Python uses 0-based indexing. It's because of slices
by EpicEng on Wednesday October 23, 2013 @10:04PM
(#6602993)
Ignoring the fact that equating what "normal people" would think in contrast to what a trained professional would think in the context of said profession, 1-indexing leads to other problems.
foreach is great, until you need an index. When you do, 0-indexing is more natural. Take, for example, looping over an image.
unsigned char *buf = get_image();
for(int y = 0; y < height; ++y) {
for(int x = 0; x < width; ++x) {
// simple
unsigned char pixel = buf[y * width + x];
}
}
That doesn't work when y begins at 1. All of a sudden you need to add and/or subtract 1 everywhere to keep things in line. I used C here, but this applies to many languages in many different circumstances where an index/count is required.
Re:Why Python uses 0-based indexing. It's because of slices
by EpicEng on Thursday October 24, 2013 @01:01AM
(#6603491)
Can't edit now, but I meant to say:
"Ignoring the fact that equating what "normal people" would think in contrast to what a trained professional would think in the context of said profession isn't always an apt comparison..."
Re:Why Python uses 0-based indexing. It's because of slices
by daviddlhg on Thursday October 24, 2013 @08:14AM
(#6604749)
fortran really lets you start from any integer index, including negative ones, 1 is just a default if you omit the lower bound. But it's not half-open when you declare (or use slicing) i.e. it uses inclusive lower and upper bounds, so A(-17:-17, 10:10) has one element not none. It might or might not have been nicer if they'd been half-open. Or one could also imagine a start+length type declaration, but meh.
http://orion.math.iastate.edu/burkardt/papers/fortran_arrays...
Fortran, Lua, Mathematica, MATLAB, Julia, and Smalltalk among current languages. Among historically important languages, COBOL, Algol68, PL/I.
> It's quite clear that it's the right solution, since the first element of an array is zero distance away from the beginning of the array.
You think it is clear because you are used to thinking of array indexes as offsets. If you think of them as ordinal numbers for describing the position in a list, then it is clear they should start at 1. If someone's grocery list is:
and you ask them "what item is #1 on your list?", most people will say bread.If you look at that list I gave of 1-based languages, you might note that many of them are oriented toward math/science/engineering. In math, both 0-based and 1-based are used. For example, matrix elements are specified by row and column number, and both of those usually start at 1. On the other hand, polynomial coefficients usually start with 0.