Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why id() in python also returns a value for literal

Tags:

python-3.x

I just started studying Python and came across id() builtin method. I found that it returns a value even for id("sudgfkasdfgalds9834710931934019734216834jefhdkdj").

As per my understanding from Python tutorials and also from What does id( ) function used for?, id() returns a memory address. So why a memory address is being returned for any random value which is not even assigned to any variable.

like image 268
Khyati Avatar asked Mar 14 '26 14:03

Khyati


1 Answers

The nature of Python is different from that of languages like C, where a variable is more-or-less a memory location.

In Python, a variable assignment can be thought of assigning a label to an object. Objects that have no labels referencing them are eventually reclaimed by the garbage collector. Multiple labels can point to the same object.

Look at the following:

In [1]: a = 1

In [2]: b = 1

In [3]: id(a), id(b)
Out[3]: (34377130320, 34377130320)

Both a and b reference the same object.

Note that in Python some type of objects (like numbers and strings) are immutable. You cannot change their instances. See:

In [4]: a += 1

In [5]: id(a)
Out[5]: 34377130352

After incementing, a points to a different object.

As an aside, when CPython starts, it creates objects for often-used small integers (like 0-100). These objects are significantly bigger than what you would normally associate with an integer. Also note that using memory addresses as id is a CPython implementation detail. So in CPython we can do:

In [6]: id(2) - id(1)
Out[6]: 32

In [7]: (id(100) - id(0))/32
Out[7]: 100.0

So in this case (64-bit FreeBSD OS, CPython 3.6) an integer object is 32 bytes.

like image 115
Roland Smith Avatar answered Mar 16 '26 04:03

Roland Smith