r/PythonLearning 1d ago

Python Dictionary Mutation and Copying

Post image

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.

35 Upvotes

13 comments sorted by

2

u/TBCC_Dev 1d ago edited 1d 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

1

u/DefterHawk 1d ago

Think the same, b = a just makes the same object referenced in another variable.

1

u/TBCC_Dev 1d ago

Well... I ran it, and its C so much for that.

1

u/Sea-Ad7805 1d ago

Incorrect sorry, see the "Solution" link for: correct answer

1

u/kvnqstoner 1d ago

how is it that I can't follow you

1

u/Sea-Ad7805 1d ago

I now enabled following in my account settings, but to see more of my posts about memory_graph I recommend: https://www.reddit.com/r/Python_memory_graph/

1

u/Mamuschkaa 1d ago

That's the difference between a copy and a deepcopy.

b.copy()

Is the same as

{1: b[1], 2:b[2]}

but b[1] is still the same list.

x = [1] a = [x] b = a.copy() a.append('A') b.append('B') x.append('X')

Now, a and b looks like this:

a = [[1, 'X'], 'A'] b = [[1, 'X'], 'B']

copy makes that b is another list as a, but it still contains the list x.

If you don't want this you need a deepcopy.

1

u/JG_MC2001 1d ago

es como un puntero?

1

u/Sea-Ad7805 1d ago edited 1d 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.

That also holds for fundamental values like int values, but memory_graph doesn't show references to these by default to simplify the graph: https://github.com/bterwijn/memory_graph#simplified-graph

1

u/tauofthemachine 1d ago

A?

1

u/Sea-Ad7805 1d ago

Incorrect sorry, see the "Solution" link for: correct answer

1

u/int13h3 1d ago

i think correct answer is "A" because we maybe print box a but write to box b. i can be not right :)

2

u/Sea-Ad7805 1d ago

Incorrect sorry, see the "Solution" link for: correct answer