[Tutor] New to this list ....

Emile van Sebille emile at fenx.com
Fri Mar 30 20:32:52 CEST 2012


On 3/30/2012 10:56 AM Prasad, Ramit said...

> Lists are mutable objects. When you pass a list to a function you bind
> a name in the functions namespace to the list object. Every name
> binding to that object will have the ability to modify the list.
>
> If you want to modify the list but not change it for others usually
> you do something like
>
> new_list = list( old_list )
> OR
> new_list = old_list[:]

Be aware though that this copies only the 'top' level objects -- if 
those object are themselves mutable you may still have issues:


 >>> a = [1,2,3]
 >>> b = [4,5,6]
 >>> c = [a,b]
 >>> d = c[:]
 >>> d.append(1)
 >>> d
[[1, 2, 3], [4, 5, 6], 1]
 >>> c
[[1, 2, 3], [4, 5, 6]]
 >>> # so far so good
...
 >>> b.append(7)
 >>> d
[[1, 2, 3], [4, 5, 6, 7], 1]
 >>> c
[[1, 2, 3], [4, 5, 6, 7]]
 >>>


To avoid this, look at copy.deepcopy as an alternative:

 >>> d = copy.deepcopy(c)
 >>> d
[[1, 2, 3], [4, 5, 6, 7]]
 >>> b.append(8)
 >>> c
[[1, 2, 3], [4, 5, 6, 7, 8]]
 >>> d
[[1, 2, 3], [4, 5, 6, 7]]
 >>>


HTH,

Emile




More information about the Tutor mailing list