Pass a list to diffrerent variables.
Jon Willeke
j.dot.willeke at verizon.dot.net
Sun May 2 10:08:28 EDT 2004
Robbie wrote:
> Peter Otten wrote:
>
>> Both methods shown above result in a (shallow) copy of the original list.
>
> Thanks, that works fine but I am working with a 2d list...
> and I dont understand why this happens
> d = [[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
> d
> [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
> f = list(d)
> f
> [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
> d[0][0]="a"
> d
> [['a', 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
> f
> [['a', 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
> What exactly is this doing? And how can I stop it?
That's why Peter cautioned that the list() constructor yields a shallow
copy. The is operator and the id() function will reveal that d[0][0]
and f[0][0] are the same list. You want the copy.deepcopy() function.
More information about the Python-list
mailing list