1

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

1

2 Answers 2

5

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[:]
Sign up to request clarification or add additional context in comments.

Comments

4

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[:]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.