Syntax Question - list multiplication
Roel Schroeven
rschroev_nospam_ml at fastmail.fm
Mon Aug 20 00:46:24 CEST 2007
Pablo Torres schreef:
> Hi guys!
>
> I am working on Conway's Game of Life right now and I've run into a
> little problem.
> I represent dead cells with 0s and live ones with 1s. Check this out:
>
> >>> grid = [[0] * 3] * 3
> >>> grid
> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
> >>> grid[0][0] = 1
> [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
>
> Now, that's not what I want. I just want the first element of the
> first sublist to be a 1, not the first of every one. Here's what I
> tried and didn't work:
>
> 0. grid = [[0] * 3][:] * 3 then the same grid[0][0] = 1 statement
> 1. grid = [[0][:] * 3] * 3 followed by the same assignment
> 2. (grid[0])[0] = 1 with the original initialization of the grid
>
> So, that means that it isn't a problem with two different variables
> refering to the same list (0. and 1. prove that). What I don't
> understand is why 2. doesn't work either. I'm baby-feeding my
> instructions to Python and the mistake is still there. Any ideas?
>
> Hope you can help. Thanks in advance,
The multiplication operator doesn't make new copies; all elements
reference the same object, as you can see with id():
>>> lst = [0] * 3
>>> lst
[0, 0, 0]
>>> id(lst[0]), id(lst[1]), id(lst[2])
(9788716, 9788716, 9788716)
As a consequence, if you modify one element, you change them all (since
it's all the same object). Solution: make sure to create independent lists.
>>> grid = [[0] * 3 for i in range(3)]
>>> grid
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> grid[0][0] = 1
--
If I have been able to see further, it was only because I stood
on the shoulders of giants. -- Isaac Newton
Roel Schroeven
More information about the Python-list
mailing list