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

4

6

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

Alston answered 24/2, 2014 at 8:58 Comment(3)
Look at your second lineFictile
Can you tag this question with the language you're using?Norvol
Yes. I want to assign value of s to s1. But I don't want to modify both variable. I just want to modify s1 and make s remain with the initial valueAlston
T
7

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

Teleost answered 24/2, 2014 at 9:3 Comment(2)
It might be useful to mention that : is a "slice operator"Norvol
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 referenceAlston
C
5

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.

Careen answered 24/2, 2014 at 9:10 Comment(0)
C
2

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.

Crump answered 24/2, 2014 at 9:2 Comment(0)
M
2

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.

Micronesia answered 24/2, 2014 at 10:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.