Neeraj-Kumar-Coder
Neeraj-Kumar-Coder

Reputation: 405

What does the id of the name of the list specify in python?

I had written a code to print the id of the name and the elements of the list:

sample_list = [1, 2, 3, 4, 5]
print(f"The id of the name of the list is = {id(sample_list)}")
for i in range(0, len(sample_list)):
    print(f"Id of element index {i} is {id(sample_list[i])}")

Output:

The id of the name of the list is = 2874211984576
Id of element index 0 is 2874206087472
Id of element index 1 is 2874206087504
Id of element index 2 is 2874206087536
Id of element index 3 is 2874206087568
Id of element index 4 is 2874206087600

I want to know why does the id of the list name is not same as the first element of the list as it was in C with arrays?

If not please tell me what does the id/address of the name of the list specify and how the members of the list is stored in the memory blocks? I recently switched to python from C.

Upvotes: 2

Views: 5213

Answers (1)

Aaron
Aaron

Reputation: 11075

TLDR: python list's are not arrays of values. They are arrays of pointers that point to values.

The exact value of id is an implementation detail of the cpython interpreter (the implementation of python developed by the python software foundation). According to the definition of the language it is only guaranteed to uniquely identify objects.

regarding cpython:

In python all objects (anything you can assign to a variable is an object) are stored in heap as a struct containing some information about reference counting, type, value, etc... The id function happens to be implemented as the value of the pointer to that struct. A python list has this same struct, and the "value" ends up being an array of pointers to other PyObject structs. These pointers have no relation to the location of the array of pointers (reference counting is another discussion), so there is no expectation for them to be in any order. Even something as simple as an integer must have one of these PyObject structs.

Upvotes: 3

Related Questions