Duplicating a variable

hnessenospam at yahoo.com hnessenospam at yahoo.com
Thu Jan 24 14:50:42 EST 2008


On Jan 24, 9:55 am, bearophileH... at lycos.com wrote:
>
> If your variable contains a list, then you can copy it like this:
>
> >>> l1 = [1, 2, 3]
> >>> l2 = l1[:]
> >>> l2[1] = 4
>
> As you can see now they are two distinct lists:
>
> >>> l1
> [1, 2, 3]
> >>> l2
>
> [1, 4, 3]
>
> If you want to copy any kind of object you can use the copy function
> (instead of a simpler copy method that's absent):
>
> >>> d1 = {1:2, 3:4}
> >>> from copy import copy
> >>> d2 = copy(d1)
> >>> d1[1] = 5
> >>> d1
> {1: 5, 3: 4}
> >>> d2
>
> {1: 2, 3: 4}
>
> But as you can see copy works only one level deep:
>
> >>> d3 = {1:[1], 3:4}
> >>> d3
> {1: [1], 3: 4}
> >>> d4 = copy(d3)
> >>> d3[1][0] = 2
> >>> d3
> {1: [2], 3: 4}
> >>> d4
>
> {1: [2], 3: 4}
>
> To copy all levels you need deepcopy:
>
> >>> from copy import deepcopy
> >>> d5 = deepcopy(d3)
> >>> d3[1][0] = 5
> >>> d3
> {1: [5], 3: 4}
> >>> d4
> {1: [5], 3: 4}
> >>> d5
>
> {1: [2], 3: 4}
>
> Bye,
> bearophile

Works great, it is exactly what I needed thanks!

-Hans



More information about the Python-list mailing list