Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Question (and answer) about deepcopy in Sage

This was driving me crazy but I just found the answer, slightly different from what I found in a link below. I will explain. I hope it may be useful to other beginners!

If you have a list of numbers and want to change one, but save the old list, no problem; you can use = as follows:

T=[1,2,3]

S=T

S[0]=5

now you find that S= [5,2,3] while T= [1,2,3]

If you do this with a list of lists, changing T changes S also, as they are identified. The way to solve this is with the copy command, either

S=T{:}

or

S=copy(T).

However, if T is a list of lists of lists, which is very easy to come across, you are in trouble. There is a Python command called "deepcopy" which deals with this.

See https://stackoverflow.com/questions/28684154/python-copy-a-list-of-lists

The point I just discovered is that to use this instead of e.g. S=copy.deepcopy(T) as suggested in the link -- this gave me an error message!!! --maybe it's ok in Pythin?? what works in SAGEMATH is simply S=deepcopy(T).

example:

T=[] S=[]

T=[[1],[2],[3]]

S=T[:]

(or equivalently S=copy(T) )

then if you do

S[0][0]=5

now both S and T are [[5],[2],[3]].

if instead you do

S= deepcopy(T)

as suggested by the links (slight modification) then this works!!! The explanation for why is in the links.

Question (and answer) about deepcopy in Sage

This was driving me crazy but I just found the answer, slightly different from what I found in a link below. I will explain. I hope it may be useful to other beginners!

If you have a list of numbers and want to change one, but save the old list, no problem; you can use = as follows:

T=[1,2,3]

S=T

S[0]=5

now you find that S= [5,2,3] while T= [1,2,3]

If you do this with a list of lists, changing T changes S also, as they are identified. The way to solve this is with the copy command, either

S=T{:}S=T[:]

or

S=copy(T).

However, if T is a list of lists of lists, which is very easy to come across, you are in trouble. There is a Python command called "deepcopy" which deals with this.

See https://stackoverflow.com/questions/28684154/python-copy-a-list-of-lists

The point I just discovered is that to use this instead of e.g. S=copy.deepcopy(T) as suggested in the link -- this gave me an error message!!! --maybe it's ok in Pythin?? what works in SAGEMATH is simply S=deepcopy(T).

example:

T=[] S=[]

T=[[1],[2],[3]]

S=T[:]

(or equivalently S=copy(T) )

then if you do

S[0][0]=5

now both S and T are [[5],[2],[3]].

if instead you do

S= deepcopy(T)

as suggested by the links (slight modification) then this works!!! The explanation for why is in the links.