Search code examples
pythonvariable-assignmentdel

Why does values of both variable change in Python?


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 :)


Solution

  • 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.).