0

Why index starts with Zero instead of One?

Here in Python, when you want to get the first element of a vector, you type vector(0), but when you to choose the first element from the end to the beginning you type vector(-1). So you see it is not symmetric. Why this? What is the benefit of ZERO being the first element in a list? Matlab for instance is more intuitive. vector(1) is the first element. The way it should be in my humble opinion.

15th Jan 2018, 3:38 PM
Robson Marini
Robson Marini - avatar
3 Respuestas
+ 8
Because it have sense behind the scene for efficiency reasons... A list of value is stored continuously in memory, each item taking the same size of memory. When you define the list, you store a reference to it in a variable, and this reference can be considerated as the memory address of the first element. So, when you want to access to the n-th element, you need to know it specific memory address, and the computation to be done is: address_of_item_n = adress_of_list + (n*size_of_one_item) ... when indexes start at zero. Else, with indexes starting at 1, the formula becomes: address_of_item_n = adress_of_list + ( (n-1) * size_of_one_item) Anyway, to clarify this concept, think about indexes as floor of a building: ground floor is floor number 0, and floor number 1 is not the first element wich fit to live ;)
15th Jan 2018, 4:10 PM
visph
visph - avatar
+ 2
because at the core arrays are memory addresses. So memory location 0 holds the value of index 0.then the next location stores the next value of index. index is the distance from first character. using this you can dereference it easily.
15th Jan 2018, 4:37 PM
shobhit
shobhit - avatar
0
understood. i was just complaining cos I m used to 1 instead of zero, and I also like symmetry. other thing that bothers me a bit is the fact that when you type a[0:3] you get the first element but not the last. it is the one before the last. I dont like that either but what the hell.... thanks anyway
15th Jan 2018, 4:13 PM
Robson Marini
Robson Marini - avatar