[Solved] Does python have something like pointer in C programming language?


This is a popular question for people who learn python.

The answer is that python has no pointer but using id(). And id() return C language memory address in CPython interpreter.

Everything in python is a python object and id() is the identity of the python object. When you write python code you need to understand how id() works, or you will waste many memory spaces. By the way, the following picture shows some real examples of how id() work in python.
enter image description here

In the CPython interpreter, the id() returns the C memory address value of PyObject. Everything in python is a python object even for the True/False value.
The description of id() in python is

Return the “identity” of an object. This is an integer that is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

There are many interpreters in Python and they can implement id(). We know the most popular one is CPython and its source code is here
https://github.com/python/cpython

And the source code to implement id() is here
enter image description here

CPython is the interpreter in C. In the source code, every python object is PyObject in C and the id() will return the C memory address of this PyObject. But remember that does not mean the interpreter should return memory address for id(). It’s just CPython interpreter do it and it is satisfied with the specification of python.

So, that’s why I say python has no pointer but id(). And CPython interpreter returns the C memory address of PyObject as the value of id().

4

solved Does python have something like pointer in C programming language?