Why does values of both variable change in Python?

mea picture mea · Feb 24, 2014 · Viewed 12.3k times · Source

I have a small piece of code and a very big doubt.

s=['a','+','b']
s1=s
print s1
del s1[1]
print s1
print s

The output is

value of s1 ['a', '+', 'b']
value of s1 ['a', 'b']
value of s ['a', 'b']

Why is the value of variable 's' changing when I am modifying s1 alone? How can I fix this?

Thank you in advance :)

Answer

vahid abdi picture vahid abdi · Feb 24, 2014

In your second line you're making new reference to s

s1=s

If you want different variable use slice operator:

s1 = s[:]

output:

>>> s=['a','+','b']
>>> s1=s[:]
>>> print s1
['a', '+', 'b']
>>> del s1[1]
>>> print s1
['a', 'b']
>>> print s
['a', '+', 'b']

here's what you have done before:

>>> import sys
>>> s=['a','+','b']
>>> sys.getrefcount(s)
2
>>> s1 = s
>>> sys.getrefcount(s)
3

you can see that reference count of s is increased by 1

From python docs

(Assignment statements in Python do not copy objects, they create bindings between a target and an object.).