appending to list
Alex Martelli
aleax at aleax.it
Wed Oct 1 12:19:23 EDT 2003
More information about the Python-list mailing list
Wed Oct 1 12:19:23 EDT 2003
- Previous message (by thread): appending to list
- Next message (by thread): appending to list
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
sud jag wrote: > Hi, > Iam a newbie to python. So any help on this is > deeply appreciated > > If I append an instance of a class to a list will > the list have a copy of the instance or just a > reference to that instance ? If it is only a reference > is there something similar to deep copy in case of > append ? A reference. Python never make copies unless you ASK for a copy, be it deep or normal (shallow) [note that deep copying is generally very expensive -- and rarely needed]. No need for "something similar to deep copy in case of append": just do thelist.append(copy.copy(theinstance)) or thelist.append(copy.deepcopy(theinstance)) depending on what exactly you need (after "import copy", of course) -- or something more sophisticated if that should be necessary. An example of "more sophisticated"...: say that your need is for all instances appended to 'thelist' to be "snapshots" from the "outside" viewpoint, BUT it's all right for them to share their own internals with each other. In this case, you may take advantage of the fact that deepcopy takes an optional "memo" dict: keep the memo (originally empty) around and pass it to every call to deepcopy. Of course, sophisticated behavior needs a good grasp of what you're doing, so, I'm not posting example code lest it tempt you, as a newbie to python, into facing stuff that's still a bit beyond your grasp; I'm just planting the seed of the idea "if and when I do need deep copies, I can take SOME limited control of the process, in certain cases, via the ``memo'' dict that deepcopy accepts" -- it will probably be quite a while before you actually NEED this information, but, who knows... Alex
- Previous message (by thread): appending to list
- Next message (by thread): appending to list
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list