I think I’m starting to understand python, but I still have trouble with a basic question. When to use copy.copy?
>>>a=5
>>>b=a
>>>a=6
>>>print b
5
Ok makes sense. But in what circumstances does saying b=a form some kind of ‘link’ between a and b such that modifying a would then modify b? This is what I don’t get about copy.copy — does every time you assign one variable to another with the equals sign just copy the value?
Basically,
b = apointsbto whereverapoints, and nothing else.What you’re asking about is mutable types. Numbers, strings, tuples, frozensets, booleans,
None, are immutable. Lists, dictionaries, sets, bytearrays, are mutable.If I make a mutable type, like a
list:They’ll both still point to the same item.
I’ll comment on your original code too:
You can always see where something points to in memory by doing
id(something).You use
copywhen you want to make a copy of a structure. However, it still will not make a copy of something that is interned. This includes integers less than256,True,False,None, short strings likea. Basically, you should almost never use it unless you’re sure you won’t be messed up by interning.Consider one more example, that shows even with mutable types, pointing one variable at something new still doesn’t change the old variable:
Slicing a list (whenever you use a
:) makes a copy.