[Tutor] could someone explain why this happens to me.

Sander Sweers sander.sweers at gmail.com
Sat Mar 7 21:23:53 CET 2009


2009/3/7 Alan Gauld <alan.gauld at btinternet.com>:
>> mycopy = original[:]
>
> Returns a slice of the original list. In this case it so happens
> the slice is the full list.
>
>> mycopy = list(original)
>
> Use the list type constructor to make a list out of its argument.
> It just so happens the argument in this case is a list.

Both not give the desired result with nested lists and this is why you have..

>> mycopy = copy.deepcopy(original)
>
> calls the deepcopy function which traverses the original list
> and all nested structures explicitly copying the elements.

copy.deepcopy :-)

>>> import copy
>>> list1 = [1,2]
>>> list2 = [3.4]
>>> list3 = [list1, list2]
>>> list4 = list(list3)
>>> list5 = list3[:]
>>> list6 = copy.deepcopy(list3)
>>> list1.append('a')
>>> list1
[1, 2, 'a']
>>> list3
[[1, 2, 'a'], [3.3999999999999999]]
>>> list4
[[1, 2, 'a'], [3.3999999999999999]]
>>> list5
[[1, 2, 'a'], [3.3999999999999999]]
>>> list6
[[1, 2], [3.3999999999999999]]

Notice that list6 is the only list which does not have the appended a.

Greets
Sander


More information about the Tutor mailing list