Frage

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

War es hilfreich?

Lösung

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

Andere Tipps

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.

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.

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top