Ian Tan
Ian Tan

Reputation: 23

Making a copy of a list

I'm trying to make a "target", a copy of "grid." I don't see why this code does not work.

grid = [[randint(0, 1), randint(0, 1), randint(0, 1)],
        [randint(0, 1), randint(0, 1), randint(0, 1)],
        [randint(0, 1), randint(0, 1), randint(0, 1)]]

target = [[0, 0, 0]] * 3
for x in range(3):
    for y in range(3):
        target[x][y] = grid[x][y]

print target
print grid

Here's a result:

[[0, 1, 0], [0, 1, 0], [0, 1, 0]]
[[1, 0, 0], [0, 1, 1], [0, 1, 0]]

Upvotes: 2

Views: 70

Answers (1)

Reut Sharabani
Reut Sharabani

Reputation: 31339

This part:

target = [[0, 0, 0]] * 3

Creates a list with the same list repeated 3 times. So changes to one item actually reflects in all (they are the same object). What you want is to create a list three times:

target = [[0, 0, 0] for _ in range(3)]

You should only use the star operator on list (or list multiplication) with immutable objects (if at all), which do not have this problem since you can't change their states.

Don't forget you can use (x[:] is used to create a shallow copy of a list named x, just like list(x)):

grid = [x[:] for x in target]

Or even more generally with copy.deepcopy:

from copy import deepcopy
grid = deepcopy(target)

Upvotes: 5

Related Questions