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

x = []
z = myfunc(x)
print(x)
  • This will help you: http://stackoverflow.com/questions/986006/python-how-do-i-pass-a-variable-by-reference – VoodooChild Jul 04 '10 at 03:52
  • 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. –  Jul 04 '10 at 04: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). – msw Jul 04 '10 at 04: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, ...). – Alex Martelli Jul 04 '10 at 04:38
  • 6
    @Ricky Demer You should edit the title. "Difficulty with Python" could be anything. – Setsuna F. Seiei Jul 04 '10 at 04:40
  • Bad title, but valid question. I'm giving it +1 to counter the downvoters. – Grant Paul Jul 04 '10 at 04:46

2 Answers2

11

You do:

y = x[:]

to make a copy of list x.

jcao219
  • 2,808
  • 3
  • 21
  • 22
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)
Petriborg
  • 2,940
  • 3
  • 28
  • 49