0

I'm stunned by this behavior, and can't seem to pinpoint what's causing the issue. I'd consider myself fluent in Python, but I'm completely at loss here.

>>> board = [[0]*3]*3

>>> board
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

>>> board[1]
[0, 0, 0]

>>> board[1][1]
0

# Expected behavior: [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
>>> board[1][1] = 1

# Actual behavior:
>>> board
[[0, 1, 0], [0, 1, 0], [0, 1, 0]]

Running Python 3.9.5 on arm64 macOS 11.4

% python3 --version
Python 3.9.5
499602D2
  • 45
  • 1
  • 1
  • 7
  • 3
    `[[0]*3]*3` creates three references to the same list, not three lists. – Carcigenicate Jun 14 '21 at 18:53
  • @Carcigenicate what a bizarre feature, this made me feel like I was in psychosis – 499602D2 Jun 14 '21 at 18:56
  • 1
    If you think about it, it would need to know how to properly copy all the internal objects for it to behave how you're expecting. Since it's a built-in list here, it could do that, but you'd need to have custom objects implement `__copy__` or something for it to be generally functioning. In general, only use `*` on a sequence if the sequence only holds immutable data. – Carcigenicate Jun 14 '21 at 18:57
  • @Carcigenicate thank you for your insight, your point makes sense. I guess I outsmarted myself trying to write things more pythonically, hah. I guess I'll stick to the good old for's instead. – 499602D2 Jun 14 '21 at 19:00

0 Answers0