Why does values of both variable change in Python?

13,869

Solution 1

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

Solution 2

The problem you're running into is that s1=s doesn't copy. It doesn't make a new list, it just says "the variable s1 should be another way of referring to s." So when you modify one, you can see the change through the other.

To avoid this problem, make a copy of s and store it into s1. There are a handful of ways to do this in Python, and they're covered in this question and its answers.

Solution 3

Here reference is same for both the variable s & s1. So if you modify 1 then other (which is same as first) will automatically gets modified.

So you need to create new instance of 's1' (syntax depends of the language) using the parameters of 's' in your code.

Solution 4

You can use "deepcopy()" here.

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

>>> import copy
>>> s = ['a','+','b']
>>> s1 = copy.deepcopy(s)
>>> print s1
['a', '+', 'b']
>>> del s1[1]
>>> print s1
['a', 'b']
>>> print s
['a', '+', 'b']

The deep copy created by deepcopy() is a new container populated with copies of the contents of the original object. For example, a new list is constructed and the elements of the original list are copied, then the copies are appended to the new list.

Share:
13,869
mea
Author by

mea

Updated on June 15, 2022

Comments

  • mea
    mea about 2 years

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

  • Blorgbeard
    Blorgbeard over 10 years
    It might be useful to mention that : is a "slice operator"
  • mea
    mea over 10 years
    Thanks Vanda. It worked but I still don't understand why Python does like this. I assumed that each one would be making a different reference