1

I have a list of strings stored in wk

I run the following code.

n_wk=wk
for i in range(10):
    if some condition:
       n_wk[i]='new'

I wanted to reserve the wk values. But, the wk is also getting changed along with n_wk. can anyone point out the error in this?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Zero
  • 74,117
  • 18
  • 147
  • 154

1 Answers1

5

Create a copy of wk:

n_wk = list(wk)

or use:

n_wk = wk[:]

both of which copy the indices over to a new list.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 2
    Because assignment doesn't always copy. Only the basic types are copied, lists, dictionaries and other objects are copied by reference, so they point to the same object. The above will also only work on lists and similar structures, consider this for more complex objects: http://docs.python.org/2/library/copy.html – Stjepan Bakrac Mar 25 '13 at 18:31
  • @StjepanBakrac: assignment *never* copies. Usually you *reassign* a new value. – Martijn Pieters Mar 25 '13 at 18:32
  • >>> a = 5 >>> b = a >>> a = 4 >>> b 5 disagrees with you. – Stjepan Bakrac Mar 25 '13 at 18:32
  • @searcoding: Because you assigned the same list to two names; that doesn't create a copy. You were modifying *the same list*. – Martijn Pieters Mar 25 '13 at 18:33
  • @StjepanBakrac: that is normal assignment. Python names are *not* pointers to a memory slot. Python variables instead are like labels tied to values. Imagine values as balloons instead. You tied `a` and `b` to the same balloon (value), but then you retied the `a` label to a *new* balloon with the int value 4. – Martijn Pieters Mar 25 '13 at 18:33
  • @StjepanBakrac: See [Python list doesn't reflect variable change, new to python](http://stackoverflow.com/questions/12080552/12080644#12080644) – Martijn Pieters Mar 25 '13 at 18:35
  • Yes, but the effect is the same. It always assigns the value of the variable, but in the case of a list, dict, etc. the value is a reference to the object, whereas in the case of a basic type it's the value itself. So using assignment on basic values is like making copies of it, even if the internals are different. – Stjepan Bakrac Mar 25 '13 at 18:38
  • @StjepanBakrac: No, they are *always* references. There is no difference between assigning a mutable and an immutable type. Only the *types* themselves differ. – Martijn Pieters Mar 25 '13 at 18:39
  • @StjepanBakrac: You are confusing changing the value with the name pointing to the value. – Martijn Pieters Mar 25 '13 at 18:40