Comment How can I get around the declaration of an unused variable in a for loop? (Ran out of comment size)
Python maintains the same reference for the created object. (regardless of variability) e.g.
In [1]: i = 1 In [2]: j = 1 In [3]: id(i) Out[3]: 142671248 In [4]: id(j) Out[4]: 142671248
You can see both i and j, refer to the same object in memory. What happens when we change the value of one immutable variable.
In [5]: j = j+1 In [6]: id(i) Out[6]: 142671248 In [7]: id(j) Out[7]: 142671236
you can see, j now starts to indicate the new location (where 2 is stored), and I still point to the place where 1. is stored. Estimating,
j = j+1
The value is selected from 142671248, calculated (if it is not already cached) and placed in a new location 142671236. j is done to indicate a new location. Simply put, a new copy made each time an immutable variable changes.
Variability
In this regard, interchangeable objects are not much different from each other. When the value is specified
In [16]: a = [] In [17]: b = a In [18]: id(a) Out[18]: 3071546412L In [19]: id(b) Out[19]: 3071546412L
Both a and b point to the same memory location.
In [20]: a.append(5)
Changed the memory location indicated by a.
In [21]: a Out[21]: [5] In [22]: b Out[22]: [5] In [23]: id(a) Out[23]: 3071546412L In [24]: id(b) Out[24]: 3071546412L
Both a and b still point to the same memory location. In other words, mutable variables act in the same memory location that the variable points to, instead of copying the value indicated by the variable, as in the immutable case of a variable.
Mohit Ranka Mar 30 '11 at 9:49 2011-03-30 09:49
source share