4 ms·
Nice, clear explanation of something that drives Python beginners crazy--especially if it's their first programming language. It would have been worth mentioni
by mjtokelly 18y ago
Nice, clear explanation of something that drives Python beginners crazy--especially if it's their first programming language.
It would have been worth mentioning the 'copy' module.
'copy.copy' for shallow copies of any object,
'copy.deepcopy' for recursive copies.
- JabavuAdams 18y agoI'm guessing, but a function that can copy any object is unlikely to be as efficient as one that works with known types. Of course, even if true, that may not matter. See, I'm all about the weasel words today.
- cstejerean 18y agoIt would be a little faster. The first part of copy.copy looks like def copy(x): """Shallow copy operation on arbitrary Python objects. See the module's __doc__ string for more info. """ cls = type(x) copier = _copy_dispatch.get(cls) if copier: return copier(x) # more after this point but it's not relevant for lists So calling copy.copy on a list over using list() will check for the type, look up the type in a dictionary after which it will proceed as if you called list() yourself.
- JabavuAdams 18y agoMental memo. :)
- palish 18y agoI'm not sure either... A hand-written .clone() method would always beat the generic solution of course, but it seems like the tradeoff is that you spend less time coding, which is a win.
- newt0311 18y agoI think addresses and pass-by-reference drive people crazy when they start
- ggrot 18y agoAgreed. The deep copy is much much better. Consider this code: >>> a = [1, [2, 3]] >>> b = list(a) # or a[:], they are identical >>> a[1].append(4) >>> a.append(5) >>> a [1, [2, 3, 4], 5] >>> b [1, [2, 3, 4]] If you had used copy.deepcopy, b would now be [1, [2, 3]] as intended.
- diN0bot 18y agothese are good points. of course, what with classes i very rarely have deep lists anyway. in fact, copying lists is seldom an issue i run into (though i always run a few tests at the prompt to make sure my understanding is right because mutability bugs can be hard to track down later).