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?

1
  • 1
    n_wk and wk are actually the same list this way. You need to explicitly copy the list. Commented Mar 25, 2013 at 18:30

1 Answer 1

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.

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

9 Comments

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: docs.python.org/2/library/copy.html
@StjepanBakrac: assignment never copies. Usually you reassign a new value.
>>> a = 5 >>> b = a >>> a = 4 >>> b 5 disagrees with you.
@searcoding: Because you assigned the same list to two names; that doesn't create a copy. You were modifying the same list.
@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.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.