You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Python has a pretty clever automatic memory manager (depending on who you ask) that takes responsibility for managing python's memory use by allocating and de-allocating memory that is used to store objects. The question was asked today if:
'a'=='a'
is comparing two instances of the data that makes up the character a in memory or if this operation is comparing the same object (physically in memory) and the variable created points to the same information that makes up the letter a.
As it turns out - this is comparing a variable that points the same information in memory. For some simple immutable values python caches them to reduce expensive operations associated with the underlying memory allocation.
In [1]: id('a')
Out[1]: 140045168580400
In [2]: var = 'a'
In [3]: id(var)
Out[3]: 140045168580400
Therefore in this case python caches the object that makes up the letter 'a' and points variables to it in the memory heap managed by python. For more complex objects this isn't necessarily the case.
In [8]: id(2**64)
Out[8]: 140045087723392
In [9]: var = 2**64
In [11]: id(var)
Out[11]: 140045087720712
In [12]: 2**64
Out[12]: 18446744073709551616
In [13]: var
Out[13]: 18446744073709551616
While the values are the same, these objects do not share the same memory id.
Python has a pretty clever automatic memory manager (depending on who you ask) that takes responsibility for managing python's memory use by allocating and de-allocating memory that is used to store objects. The question was asked today if:
is comparing two instances of the data that makes up the character
a
in memory or if this operation is comparing the same object (physically in memory) and the variable created points to the same information that makes up the lettera
.As it turns out - this is comparing a variable that points the same information in memory. For some simple immutable values python caches them to reduce expensive operations associated with the underlying memory allocation.
Therefore in this case python caches the object that makes up the letter 'a' and points variables to it in the memory heap managed by python. For more complex objects this isn't necessarily the case.
While the values are the same, these objects do not share the same memory id.
Further Reading
http://foobarnbaz.com/2012/07/08/understanding-python-variables/
The text was updated successfully, but these errors were encountered: