why this happend using model random?
Robert Kern
rkern at ucsd.edu
Tue May 10 07:57:56 EDT 2005
flyaflya wrote:
> Robert Kern wrote:
>
>>flyaflya wrote:
>>
>>
>>>from random import *
>>>
>>>col = [0 for i in range(10)]
>>>a = [col for i in range(10)]
>>
>>
>>This is the problem. The list "a" now has ten references to the same
>>object "col". They are not copied.
>>
>>
>>>seed()
>>>for i in range(10):
>>> for j in range(10):
>>> a[i][j] = randint(0, 100)
>>
>>
>>So every time you index into "a[i][j]" you are always getting "col[j]".
>>
>
> thanks,I see,I know about reference and copy,but when is it a copy?when
> a reference?how can I get a copy when need?
Usually, references get passed around wherever possible. Just putting
"col" into the list comprehension like you did will never copy.
If you need a copy of a list, you could do "col[:]" or "list(col)". More
generally, see the "copy" module.
--
Robert Kern
rkern at ucsd.edu
"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
More information about the Python-list
mailing list