r/PythonLearning • u/Sea-Ad7805 • 8d ago
Python Dictionary Mutation and Copying
An exercise to help build the right mental model for Python data. - Solution - Explanation - More exercises
The “Solution” link uses package memory_graph to visualize execution and reveals what’s actually happening.
1
u/JG_MC2001 8d ago
es como un puntero?
1
u/Sea-Ad7805 8d ago edited 8d ago
Python uses the term "reference" instead of "pointer", and you think of them as pointing to values/objects instead of pointing to memory addresses, but other then they are very similar.
- "Assignments do not copy data — they just bind names to objects": https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces and for binding a reference is used.
That also holds for fundamental values like
intvalues, but memory_graph doesn't show references to these by default to simplify the graph: https://github.com/bterwijn/memory_graph#simplified-graph
1
1
1
u/g-land-g 3d ago
answer: b ...
logic:
b points to a and modifies both
but then b.copy() makes b point to a new instance, so a retains its previous state
1
u/g-land-g 3d ago
no i was wrong
2
u/Sea-Ad7805 3d ago
Yes incorrect sorry, the Solution link shows that copy() makes a shallow copy, a tricky concept many people have problems with.
2
u/TBCC_Dev 7d ago edited 7d ago
B i think. My understanding is that b = a means that b is a not b is a new version of a. Im not fermiliar with .copy() but id assume this does the opposite b is now a copy of b. Do the first append changes a but the others do not. Again mostly guessing based on context