python - Making a copy of a list -
i'm trying make "target", copy of "grid." don't see why code 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 x in range(3): y in range(3): target[x][y] = grid[x][y] print target print grid
here's result:
[[0, 1, 0], [0, 1, 0], [0, 1, 0]] [[1, 0, 0], [0, 1, 1], [0, 1, 0]]
this part:
target = [[0, 0, 0]] * 3
creates list same list repeated 3 times. changes 1 item reflects in (they same object). want create list 3 times:
target = [[0, 0, 0] _ in range(3)]
you should use star operator on list (or list multiplication) immutable objects (if @ all), not have problem since can't change states.
don't forget can use (x[:]
used create shallow copy of list named x
, list(x)
):
grid = [x[:] x in target]
or more copy.deepcopy
:
from copy import deepcopy grid = deepcopy(target)
Comments
Post a Comment