r/PythonLearning • u/Sea-Ad7805 • Jul 14 '26
Python Data Model Exercise
An exercise to help build the right mental model for Python data.
The โSolutionโ link visualizes execution and reveals whatโs actually happening using ๐บ๐ฒ๐บ๐ผ๐ฟ๐_๐ด๐ฟ๐ฎ๐ฝ๐ต.
67
Upvotes
1
u/FoolsSeldom Jul 14 '26 edited Jul 14 '26
C.
Line 4 re-assigns
bto a newlistobject so severs the link to the originallistobject referenced byaandbup to that point.EDIT: More detail for learners regarding variables and lists in Python (on back of a challenge from u/HardyDaytn):
Variables in Python do not contain values, but simply reference where in Python a Python object (
int,float,str,list, etc) is located in memory. Generally, you don't need to concern yourself with the memory matters.A Python
listobject similarly does not contain any variables or values, but only a collection of zero or more references to other Python objects.Two variables can reference the same object and if the object is mutable (able to be changed), such as a
list, then changing the object can be done via either variable.Thus,
This does the following:
Assigns a memory reference to the pre-defined
intbinary object representation of decimal 10 to the variable namealphaAssigns a memory reference to the new
strobject (consisting of binary unicode numbers for each character in the string) to the variable namebetaAssigns the memory reference to the new
floatbinary object representation of the decimal floating point number 12.1 to the variable namecharlieAssigns the memory reference to the new
listobject, containing 3 entries to newstrobjects, to the variable namedelta, where each entry in thelistis itself a memory reference to a new Python objectAssigns the memory reference to the new
listobject, containing 4 entries, to the variable namestuff, where each entry in thelistis itself a memory reference to a Python object as below,the first entry in the
listholds the same memory reference asalphaholdsthe second entry in the
listholds the same memory reference asbetaholdsthe third entry in the
listholds the same memory reference ascharlieholdsthe fourth entry in the
listholds the same memory reference asdeltaholds, i.e. they both refer to the samelistobjectIt is worth noting that if you change the contents of the
listreferenced bydelta, that change will also show up in thelistreferenced bystuff. This is shown in the example below.Complete code:
Outputs,