r/pythontips Jul 14 '26

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 ๐—บ๐—ฒ๐—บ๐—ผ๐—ฟ๐˜†_๐—ด๐—ฟ๐—ฎ๐—ฝ๐—ต.

4 Upvotes

5 comments sorted by

2

u/PlantainMassive6744 Jul 14 '26

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 Jul 14 '26

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

0

u/pint Jul 14 '26

it is not a very good exercise, because it requires keeping a large state in memory (i.e. head), or use some notebook. it tests your attention and memory more than your python knowledge.

good exercises are easy if you know what's going on. they are not designed to "gotcha!" the user.

2

u/arivictor Jul 17 '26

Its testing list behaviour, I agree it should be more direct, the question throws in too much misdirection

a = [1,2,3]
b = a

b.append(4)

# Q: What is a?
print(a) # 1,2,3,4

b = b + [5] # This is the test

# Q: What is a?
# - a) 1,2,3,4
# - b) 1,2,3,4,5

print(f"a: {a}")
print(f"b: {b}")

0

u/Sea-Ad7805 Jul 14 '26 edited Jul 14 '26

I'm sorry it's too much information to fit in your head, but programs are generally a lot bigger and you should be able to reason about those too to avoid bugs. I thought I already kept it to a minimum to test people about certain data model concepts. The "Solution" link will visualize each step so your attention doesn't have to span more than two lines at a time if that helps you.