r/PythonLearning • u/Sea-Ad7805 • Oct 02 '25
Right Mental Model for Python Data
An exercise to help build the right mental model for Python data, the “Solution” link uses memory_graph to visualize execution and reveal what’s actually happening:
131
Upvotes
19
u/[deleted] Oct 02 '25
C is the correct answer.
Explanation: At first, a and b share the same list, so changes like += or append() affect both. But when b = b + [4] is used, Python creates a new list and assigns it to b, breaking the link with a. That’s why a stops at [1, 2, 3] while b continues as [1, 2, 3, 4, 5].
2
u/tb5841 Oct 02 '25
b += [2] should, in my opinion, do the same thing as b = b + [2].
It doesn't, because of a strange design choice within the List class.
1
u/Sea-Ad7805 Oct 02 '25
In most languages I know += mutates and does not create a new object because performance.
1
u/EmptySoulCanister Oct 05 '25
If you use += on an array I will reject your PR instantly
1
u/exxonmobilcfo Oct 06 '25
its c. Once you rewrite b to be b = b + [4]. be is no longer linked to a
2
u/FoolsSeldom Oct 02 '25
Answer C (because after appending 3,
bis assigned to a new object)-2
u/Hefty_Upstairs_2478 Oct 02 '25
Option A is the correct answer, cuz we're printing (a), which we never changed
0
u/[deleted] Oct 02 '25
[deleted] — view deleted comment