Why element search starts with [0] in python?

why the elements search starts with [0] in python? It can start with [1]

2 Likes

honestly - thats a “why does the sun rise in the east” question. first index is 0 in Python, thats just the way it is. and yes - you can start counting from index 1, that doesnt change its the second item in your list.

Because it follows C++ indexing methods…

1 Like

The most common answer to the array/list(in python) numbering question, points out that zero-based numbering comes from language design itself. In C an array points to the location in the memory, so in expression array[ n ] , n should not be treated as an index, but as an offset from the array’s head.(python is written in C so it follows the same rules)
Run the following program

#include <stdio.h>
int main()
{
    int data[6] = {1, 2, 3, 4, 5, 6};
    int i = 0;
  
    printf("Array address: %p\n", data);
  
    do {
        printf("Array[%u] = %p\n", i, (void *)(&data[i]));
        i++;
    } while(i < 6);
}

Output


Array address: 0x7ffe9472bad0
Array[0] = 0x7ffe9472bad0
Array[1] = 0x7ffe9472bad4
Array[2] = 0x7ffe9472bad8
Array[3] = 0x7ffe9472badc
Array[4] = 0x7ffe9472bae0
Array[5] = 0x7ffe9472bae4

As we can see on this example, the first element and the array itself points to the same memory location, so it is 0 elements away from the location of the array itself.

more refer this article http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html

1 Like