3

I have the following function:

def myfunc(x):
    y = x
    y.append(' appendix') # change happens here
    return y

x = []
z = myfunc(x)
print(x) # change is reflected here, and appendix is printed

how can I assure that changes x aren't reflected in the code that calls the function?

5
  • People who are downvoting my question: How should I have known about this? The style I gave would work in every other language I have used. Commented Jul 4, 2010 at 4:02
  • @ricky: I rarely downvote and didn't here, but in answer to your question, you are right Python assignment is different than many other languages, but I'm guessing the downvoters are thinking something like "RTFM". Regardless, for your own sake, don't sweat one downvoted question (if it happens a bunch, you should probably try to figure out why). Commented Jul 4, 2010 at 4:24
  • @Ricky, I'm no downvoter either, but note that in Java -- perhaps the single most widespread programming language, certainly the most taught in college today -- assignment is by reference, just like in Python. Perhaps the downvoters just intrinsically think in those terms (rather than, say, in terms of Fortran, Pascal, C, ...). Commented Jul 4, 2010 at 4:38
  • 6
    @Ricky Demer You should edit the title. "Difficulty with Python" could be anything. Commented Jul 4, 2010 at 4:40
  • Bad title, but valid question. I'm giving it +1 to counter the downvoters. Commented Jul 4, 2010 at 4:46

2 Answers 2

11

You do:

y = x[:]

to make a copy of the collection in x. Note that this is a shallow copy, so if the elements in the collection are mutable then those values can still be changed by the function - but for a list of characters this will work fine. For strings - immutable in Python - the copy is not required.

Sign up to request clarification or add additional context in comments.

4 Comments

It's worth noting that the copy is shallow.
@FMc and jcao219 Could you take a quick look to see if the changes made make sense for this old answer?
@MaartenBodewes IMHO, you should delete the edit as unnecessary. Anyone interested in the topic of shallow copying can easily find it on StackOverflow. Alternatively, you could delete the edit and just add a link or two to such discussions. Either way, don't explain the concept here.
@FMc If've tried to shorten it somewhat. Not explaining this while the question is about mutability of a parameter is a step too far for me.
1

You need to copy X before you modify it,

def myfunc(x):
 y = list(x)
 y.append('How do I stop Python from modifying x here?')
 return y

x = []
z = myfunc(x)
print(x)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.