












Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!













0x 100 0 0x 100 1 0x 100 2 0x 100 3 0x 100 4 0x 100 5 … Heap … object 1 object 2 object 3 Memory Address Python Memory Manager Memory
In Python, we can find out the memory address referenced by a variable by using the id() function. This will return a base-10 number. We can convert this base-10 number to hexadecimal, by using the hex() function.
a = 10 print(hex(id(a)))
Finding the Reference Count ctypes.c_long.from_address(address).value
passing my_var to getrefcount() creates an extra reference!
Python, in contrast, is dynamically typed.
The variable my_var is purely a reference to a string object with value hello. No type is “attached” to my_var.
The variable my_var is now pointing to an integer object with value 10. myVar String Hello
Int 10 0x
We can use the built-in type() function to determine the type of the object currently referenced by a variable. Remember: variables in Python do not have an inherent static type. Instead, when we call type(my_var) Python looks up the object my_var is referencing (pointing to), and returns the type of the object at that memory location.
my_var = 10 my_var in t 1 5 0x int 10 0x my_var = 15
int 15 0x int 10 0x
In fact, the value inside the int objects, can never be changed!
Consider an object in memory: type state (data) 0x
BankAccou nt Acct #: 12345 Balance: 150 0x BankAccount Acct #: 12345 Balance: 500 0x my_account
internal state (data) has changed
An object whose internal state can be changed, is called Mutable An object whose internal state cannot be changed, is called Immutable
t = (1, 2, 3) a = [1, 2] b = [3, 4] t = (a, b) But consider this: Lists are mutable: elements can be deleted, inserted, or replaced t = ([1, 2], [3, 4]) Tuples are immutable: elements cannot be deleted, inserted, or replaced In this case, both the container (tuple), and all its elements (ints) are immutable a.append(3) b.append(5) t =^ ([1,^ 2,^3 ],^ [3,^ 4,^5 ]) In this case, although the tuple is immutable, its elements are not. The object references in the tuple did not change but the referenced objects did mutate!
t = (1, 2, 3) tuple is immutable these are references to immutable object (int)
tuple is immutable these are references to a mutable object (list)