2

How variables work in python? I tried understand it by assigning a value to a variable(a) and checking memory address of it.But,when I changed the value of that variable(a),I got another memory address.what is the reason for that? and that memory address is in the stack area of the memory? and the scope of it?,when I call del a,only variable identifier('a') was deleted.but,It is still on the memory.After,I call id(3),then,that memory address in the code section of the memory?and how python variables stored in memory?,anyone can explain more?

Code:

#!/usr/bin/python3
import _ctypes
a=45
s=id(a)
print(s)
a=a+2
d=id(a)
print(d)
print(_ctypes.PyObj_FromPtr(s))
del a
print(_ctypes.PyObj_FromPtr(d))
print(id(3))

Output:

10915904
10915968
45
47
10914560
4
  • 2
    Read this: nedbatchelder.com/text/names.html Commented Jun 19, 2020 at 19:23
  • In short, variables are just names that refer to objects, the variable itself is not a location in memory, like in C. Also, small int objects are cached by the interpretor, which is why you are getting the same id over and over. All python objects are allocated on a privately managed heap Commented Jun 19, 2020 at 19:24
  • Does this answer your question? Are python variables pointers? or else what are they? Commented Jun 23, 2020 at 15:15
  • There are no pointers available in python.they are references for arrays. Commented Jun 23, 2020 at 16:50

1 Answer 1

2

What you're seeing is an optimization detail of CPython (the most common Python implementation, and the one you get if you download the language from python.org).

Since small integers are used so frequently, CPython always stores the numbers -5 through 256 in memory, and uses those stored integer objects whenever those numbers come up. This means that all instances of, say, 5 will have the same memory address.

>>> a = 5
>>> b = 5
>>> id(a) == id(b)
True
>>> c = 4
>>> id(a) == id(c)
False
>>> c += 1
>>> id(a) == id(c)
True

This won't be true for other integers or non-integer values, which are only created when needed:

>>> a = 300
>>> b = 300
>>> id(a) == id(b)
False
Sign up to request clarification or add additional context in comments.

1 Comment

Then,script is loaded to ram,initially,it creates variables for numbers(-5 to 256).But,they are located on what section of memory? global area?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.