Home > Blockchain >  What does CPython do when we access an element of the list by index?
What does CPython do when we access an element of the list by index?

Time:12-01

Can you please explain the process that is performed on the background when we access an element of the list by index?

My knowledge of C is pretty limited, thus I cannot fully understand the source code. So far I have identified this function declaration as the relevant one.

Based on this article, my understanding is that a list is an array of pointers. Once the list is created, the list structure contains the length and the allocated memory which is normally greater than size. However, I do not understand the following:

When we access an element, do we make use of length of the list? Or we just access the pointer ob_item[i]?

The following question does not answer this one as it only covers list implementation.

CodePudding user response:

C doesn't check if the index and I assume CPython neither. This means that when you try to access an element in a list, it will be assumed the index is not out of bounds. This means it's up to the programmer to perform those checks using the length of the list. In the code you provide, there is a function valid_index(...) that does this.

CodePudding user response:

Python uses the length of the list you're indexing to check if the index is out of range. It doesn't need the length for the actual indexing step, but C doesn't have any protection against indexing beyond the end of an array, so checking the length first is important.

It's worth noting that the function you linked is not the function that implements indexing from Python code. Rather, it is a C API function that is mostly intended for other C code to use. The function that actually gets called when you index a list from Python code is called list_subscript which you can see further down the source code. That function handles negative indexes (and slices) and then calls another function to do the actual indexing. For integer indexes, it calls list_item, which is almost the same as the more generic PyList_GetItem you were looking at (PyList_GetItem includes a check that confirms the object it's being called on is actually a list).

  • Related