[Tutor] Copying [was Re: What's in a name?]
Mark Lawrence
breamoreboy at yahoo.co.uk
Sat Jan 4 06:50:35 CET 2014
On 04/01/2014 05:44, Steven D'Aprano wrote:
> On Fri, Jan 03, 2014 at 01:53:42PM -0500, Keith Winston wrote:
>
>> That's what I meant to do: make a copy when I wrote chute_nums = chutes. So
>> I should have passed chute_nums to summarize_game, but it still wouldn't
>> work (because it's not a copy).
>
> Python never makes a copy of objects when you pass them to a function or
> assign them to a name. If you want a copy, you have to copy them
> yourself:
>
> import copy
>
> acopy = copy.copy(something)
>
>
> ought to work for just about anything. (Python reserves the right to not
> actually make a copy in cases where it actually doesn't matter.)
>
> There are a couple of shortcuts for this:
>
> # copy a dictionary
> new = old.copy()
>
> # copy a list, or tuple
> new = old[:] # make a slice from the start to the end
>
>
Please be aware of the difference between deep and shallow copies see
http://docs.python.org/3/library/copy.html
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Tutor
mailing list