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 :)
You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.
Assigning one variable to another variable creates an alias of each variable. An alias is variable that points to the same object in memory as another variable. In the example above, both variables var1 and var2 are aliases of each other. In Python, it is possible to destroy references.
Answer: Yes — the scopes will not overlap so there will be two local variables, one per method, each with the same name.
Copy an object using = operator in python For example, if we have a variable named var1 referring to an object and we assign var1 to var2 by the statement var2=var1 , both the variables point to the same object and thus will have the same ID.
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.).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With