0

this is as much a conceptual question as a concrete one, and I haven't seen anyone ask this yet. When reassigning an element of a list using Python's built-in .replace() function, I'm finding that not only the desired list is reassigned, but the original list that it was derived from is reassigned as well. This is probably best explained using an example:

> x = ['apple','banana','potato']
> y = x
> print x;print y
 ['apple','banana','potato']
 ['apple','banana','potato']

Now, if I try to reassign an element of y using .replace(), it also reassigns to x:

> y[0] = y[0].replace('e','3')
> print x; print y
 ['appl3','banana','potato']
 ['appl3','banana','potato']

Now I have lost my original x variable, which I wanted to keep. Can anyone explain why this is happening and/or how to avoid this?

0 Answers0