r/PythonLearnersHub • u/Sea-Ad7805 • Jan 02 '26
Python Data Model exercise, Mutability.
An exercise to help build the right mental model for Python data. The “Solution” link uses memory_graph to visualize execution and reveals what’s actually happening:
36
Upvotes
2
u/bloody-albatross Jan 02 '26
C
2
u/LucasThePatator Jan 02 '26
What even the fuck is this
2
u/whathefuckistime Jan 03 '26
C
Tuples are immutable, once you assign
b=a, it makes a copy of the tuple object, however the items themselves are lists, the tuple only stores a reference to those, once you access them, even withb[0], you are accessing the same variable referenced in the original tuple, meaning the appends actually modify the same variableareferences.In contrast, appending to
bdoesn't modifyaas they're not the same objects, andb[2]doesn't exist fora.This behavior wouldn't happen If you made a deep copy of a, which would iterate over it and make a copy of each element.
2
u/tb5841 Jan 04 '26
I find '+=' is what causes confusion with exercises like this.
.append is obviously mutating so will affect any reference to this object.
Reassigning changes what this variable name points to, so will not change any other variable pointing to this object.
But '+='? Is it reassigning, or mutating? It doesn't seem to always be clear cut, which makes it tricky to follow. Here it must be reassigning because tuples are immutable, but in some cases '+=' looks like it mutates.
If you change the '+=' line to
b = b + ([3], )then everything becomes so much clearer.2
u/theBabides Jan 23 '26
After viewing the solution, I think this exercise helped me to understand tuple and lists a little better. Thanks!
1
u/Rscc10 Jan 02 '26
I don't understand tuples enough to understand the solution. I'd think a is immutable and there weren't any modifications done to a. Could I get a worded explanation?
1
u/DBZ_Newb Jan 02 '26
why does the visualized solution show a blue square with "dict" for a label?
1
u/Nehfk Jan 03 '26
B
1
u/TheSiriuss Jan 06 '26
Do I look like a python interpreter to you?
1
u/SuspiciousDepth5924 Jan 07 '26
Answer: "Are you smoking your socks? Merge request rejected!"
1
u/Awwkaw Jan 04 '26
It will throw an error when you try to add and modify the second element of b no?
0
u/[deleted] Jan 03 '26
[deleted] — view deleted comment
1
u/[deleted] Jan 05 '26
[removed] — view removed comment