开发者

python variables

开发者 https://www.devze.com 2023-03-01 15:38 出处:网络
I have a simple question. i read a string from file and stored in in a list (named:formula). Then i stored (formula) in another variable (fstore = formula) to keep it for later. Then i made changes to

I have a simple question. i read a string from file and stored in in a list (named:formula). Then i stored (formula) in another variable (fstore = formula) to keep it for later. Then i made changes to formula, and as it turns out, fstore is changing as开发者_Python百科 well. Why does this keep happening? I want fstore to remain constant. I didnt use fstore anywhere else in the program. Is my assignment (fstore = formula) wrong?

Jay


The important distinction here is between mutable and immutable data types. In python, a list is mutable, while a tuple is immutable. This means that when you "change" the value of a tuple like this:

t1 = (1, 2, 3)     # t1 points to (1, 2, 3)
t2 = t1            # t2 points to the same tuple as t1
t1 = (2, 3, 4)     # t1 points to a new tuple (2, 3, 4)

you're actually creating a brand new tuple and assigning t1 to point to that new tuple. t2 still points to the old tuple, which cannot be changed, because tuples are immutable. In short, if you assign an immutable value to a variable, you can assume that value will never change -- unless you explicitly assign a new value to the variable.

But when you change the value of a list, you actually change the list itself:

l1 = [1, 2, 3]     # l1 points to [1, 2, 3] 
l2 = l1            # l2 points to the same list as l1
l1[0] = 5          # now [1, 2, 3] becomes [5, 2, 3]

Since l1 and l2 both point to the same list, they both change when one of them changes.

To make a copy that won't change when l1 changes, simply use list:

l2 = list(l1)

Or use slice notation:

l2 = l1[:]


Remember that those names in Python aren't VARIABLEs, they're REFERENCES to variables. So you're ending up with two aliases to one piece of store. Have a look at the copy module, or use this:

 cpy = mystr[:]
0

精彩评论

暂无评论...
验证码 换一张
取 消