Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.



Agreed. 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.


these 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).


I'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.


It 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.


Mental memo. :)


I'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.


I think addresses and pass-by-reference drive people crazy when they start




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: