I am trying to clarify for myself Python's rules for 'assigning' values to variables.
Is the following comparison between Python and C++ valid?
In C/C++ the statement
int a=7
means, memory is allocated for an integer variable calleda
(the quantity on the LEFT of the=
sign) and only then the value 7 is stored in it.In Python the statement
a=7
means, a nameless integer object with value 7 (the quantity on the RIGHT side of the=
) is created first and stored somewhere in memory. Then the namea
is bound to this object.
The output of the following C++ and Python programs seem to bear this out, but I would like some feedback whether I am right.
C++ produces different memory locations for a
and b
while a
and b
seem to refer to the same location in Python
(going by the output of the id() function)
C++ code
#include<iostream>
using namespace std;
int main(void)
{
int a = 7;
int b = a;
cout << &a << " " << &b << endl; // a and b point to different locations in memory
return 0;
}
Output: 0x7ffff843ecb8 0x7ffff843ecbc
Python: code
a = 7
b = a
print id(a), ' ' , id(b) # a and b seem to refer to the same location
Output: 23093448 23093448