0

I initialized an empty 2-dimensional list in python:

memories = []
for idx in range(x_size):
    memories.append([Dot(0,0)]*y_size)

where Dot is a class:

def __init__(self, x, y):
        self.x = x
        self.y = y

Afterwards, I fill the list memories with content, as follows:

memories[p.state.x][p.state.y].y += 1

The problem is that for some reason, the new value is updated not only in the single cell memories[p.state.x][p.state.y] but rather also in the whole row memories[p.state.x]. Why does this happen and how can I avoid it?

Thanks :)

Cheshie
  • 2,777
  • 6
  • 32
  • 51
  • 1
    `for i in memories[0]: print(id(i))` :P you have a list of pointers to the same list, not a list of lists. – NightShadeQueen Jul 12 '15 at 20:06
  • 1
    Don't use `([Dot(0,0)]*y_size)` use `([Dot(0,0)]for _ in range(y_size))`. `([Dot(0,0)]*y_size)` creates y_size references to the same object – Padraic Cunningham Jul 12 '15 at 20:07
  • @PadraicCunningham - really?! But when I create an empty list, like: `a = [0]*size` - it creates a, well, a _real_ list, not references... unless I'm mistaken? Thanks anyway. I guess you're right, I'm just wondering about the reason. – Cheshie Jul 12 '15 at 20:12
  • 1
    ints are immutable, the above should also be `([Dot(0,0) for _ in range(y_size)])` – Padraic Cunningham Jul 12 '15 at 20:13

0 Answers0