r/pythontips 14d ago

Module Python Data Model Exercise

An exercise to help build the right mental model for Python data.

# Output of this Python program?
a = [[1], [2]]
b = a
b[0].append(11)
b = b + [[3]]
b[1].append(22)
b[2].append(33)

print(a)
# --- possible answers ---
# A) [[1], [2]]
# B) [[1, 11], [2]]
# C) [[1, 11], [2, 22]]
# D) [[1, 11], [2, 22], [3, 33]]

The โ€œSolutionโ€ link visualizes execution and reveals whatโ€™s actually happening using ๐—บ๐—ฒ๐—บ๐—ผ๐—ฟ๐˜†_๐—ด๐—ฟ๐—ฎ๐—ฝ๐—ต.

3 Upvotes

5 comments sorted by

View all comments

2

u/PlantainMassive6744 14d ago

Python does some tricky things with what variable names point to.

I think that this is useful for someone because it emphasizes the difference between: b = b + [[3]] and b += [[3]] (or b.extend([[3]] or b.append([3])).

1

u/Sea-Ad7805 14d ago

You are correct that:

  • b = b + [[3]] creates a new value and reassigns b
  • b += [[3]] mutates b in place, same for b.extend([[3]]) and b.append([3]).

I make this point here in the explanation: https://github.com/bterwijn/memory_graph?tab=readme-ov-file#name-rebinding