[Tutor] Copying [was Re: What's in a name?]

Steven D'Aprano steve at pearwood.info
Sat Jan 4 06:44:59 CET 2014


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


-- 
Steven


More information about the Tutor mailing list