Question (and answer) about deepcopy in Sage

asked 2018-11-20 01:55:41 +0200

al gravatar image

updated 2018-11-20 01:56:30 +0200

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/2...

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.

edit retag flag offensive close merge delete

Comments

To display blocks of code or error messages, skip a line above and below, and do one of the following (all give the same result):

  • indent all code lines with 4 spaces
  • select all code lines and click the "code" button (the icon with '101 010')
  • select all code lines and hit ctrl-K

For instance, typing

If we define `f` by

    def f(x, y, z):
        return x * y * z

then `f(2, 3, 5)` returns `30` but `f(2*3*5)` gives:

    TypeError: f() takes exactly 3 arguments (1 given)

produces:

If we define f by

def f(x, y, z):
    return x * y * z

then f(2, 3, 5) returns 30 but f(2*3*5) gives:

TypeError: f() takes exactly 3 arguments (1 given)

Please edit your question to do that.

slelievre gravatar imageslelievre ( 2018-11-21 08:20:30 +0200 )edit

Also, please separate the answer from the question. The question should be a question, and the answer should be posted as an answer, for clarity.

slelievre gravatar imageslelievre ( 2018-11-21 08:21:05 +0200 )edit