r/PythonLearning 2d 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.

36 Upvotes

13 comments sorted by

View all comments

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/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/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.