0

In Python we declare and assign a variable like this:

a = 100

Most tutorials say a variable a now refers to the int object 100.

Does that mean the variable a contains the address where an int object is stored ?

Cody
  • 2,480
  • 5
  • 31
  • 62
  • 3
    Indirectly somewhere behind the scenes yes. Not that it would concern you in userland code, since you have no direct access to memory. – deceze Jun 21 '17 at 12:45
  • Variables don't store anything in Python. Python doesn't really have variables, it has names which are stored in a dictionary. – John Coleman Jun 21 '17 at 12:45
  • yes it points to the address where 100 located – Sanket Jun 21 '17 at 12:45
  • 2
    Alright, awesome consistency among comments here. :-D – deceze Jun 21 '17 at 12:46
  • @deceze Yes, I mean behind the scenes. So it acts like a pointer? – Cody Jun 21 '17 at 12:47
  • @deceze lol! To my understanding Python does bind names to variables however it does not work like pointers in C. – Ludisposed Jun 21 '17 at 12:47
  • https://docs.python.org/2/reference/executionmodel.html – Ludisposed Jun 21 '17 at 12:48
  • @Cody You must not think of Python variables as pointers à la C, no. – deceze Jun 21 '17 at 12:50
  • @deceze that depends on what you mean by "think of Python variables as pointers". There is an element of truth in that perspective. For one thing, it explains how it is easy to create unintentional aliases when you do something like `a = b` with a mutable `b`. – John Coleman Jun 21 '17 at 12:55
  • @John Sure, but if you think in those terms then at some point you'll crash into things that *don't* work with variables that work with pointers, like pointer arithmetic. Thinking in terms that Python uses to describe itself has less cognitive overhead in the long run. – deceze Jun 21 '17 at 12:58

1 Answers1

0

As John Coleman points out, python variables are just names in a dictionary, where the values pointed to by the keys are addresses. In the CPython implementation of python, you can find the memory address pointed to by a python variable by using the built-in function id().

For more information about this dictionary refered to in my answer, see this StackOverflow post

Will Da Silva
  • 6,386
  • 2
  • 27
  • 52