Pass a list to diffrerent variables.

Peter Otten __peter__ at web.de
Sun May 2 10:06:38 EDT 2004


Robbie wrote:

> 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?

While you have copied the outer list, both d and f share the same items, e.
g. d[0] and f[0] refer to the same item (a list containing 1,2,3 in this
case). That is called a "shallow" copy. To avoid such sharing, you need to
copy not only the outer list but also recursively the data it contains.
This is called a "deep" copy and can be done with the copy module:

>>> import copy
>>> a = [[1,2,3], [4,5]]
>>> b = copy.deepcopy(a)
>>> a[0][0] = "a"
>>> b[0][0]
1
>>>

A word of warning: I've never used this module in my code and think its
usage is a strong indication of a design error in your application. (Of
course I cannot be sure without knowing what you actually try to achieve.)

Peter




More information about the Python-list mailing list