Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does values of both variable change in Python? [duplicate]

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

like image 484
mea Avatar asked Feb 24 '14 08:02

mea


People also ask

How do I make two variables the same value in Python?

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.

What happens when you assign the value of one variable to another variable in Python?

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.

Can two variables have the same name Python?

Answer: Yes — the scopes will not overlap so there will be two local variables, one per method, each with the same name.

How do you copy the value of a variable in Python?

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.


2 Answers

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

like image 124
vahid abdi Avatar answered Oct 07 '22 05:10

vahid abdi


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.

like image 30
pandubear Avatar answered Oct 07 '22 06:10

pandubear