DEV Community

Discussion on: Dead Simple Python: Data Typing and Immutability

Collapse
 
nachiketrss profile image
nachiketrss • Edited

Hi, you have shared some brilliant knowledge, very helpful. Thanks. Please can you give some more details on the below statement:
"Many data types in Python are immutable, meaning only copy of the data exists in memory, and each variable containing that data just points to that one master copy. Mutable types, on the other hand, don't do this."

Bit confused with the term master copy here. And what you mean by mutable types don't do this.

I know that List/Set/Dict is mutable; Tuple is immutable. And my understanding is that - mutable types point to one single master copy, and doing an operation like append will update that master copy thus making changes reflect on all variables. Example:
l1=[1,2,3]
l2=l1 #points to same location as pointed by l1
l3=l2 #points to same location as pointed by l1
l4=l3 #points to same location as pointed by l1
l2.append(100) #updates the same location, thus all will point to [1,2,3,100]

Where as assignment will make that particular variable point to a different location. Example:
l5=l1 #points to same location as pointed by l1
l5=[5,6,7] #l5 now points to [5,6,7]. l1, l2, l3, l4 still continue to point at [1,2,3,100]

In case of immutable type - each assignment points to its own separate copy (and not master copy). Operation like append is not supported.

Please correct me.

Collapse
 
codemouse92 profile image
Jason C. McDonald

You've got the list examples exactly right. That's how mutable copies work.

Regarding immutable types, like tuples, the first part is the same.

t1 = (1,2,3)
t2 = t1 #points to same location as pointed by t1
t3 = t2 #points to same location as pointed by t1
t4 = t3 #points to same location as pointed by t1

You are correct that an immutable type doesn't support append. As the word "immutable" suggests, the value cannot be mutated, or modified.

However, we can reassign.

t3 = (4,5,6) # t3 now points to (4,5,6). t1, t2, t4 still point to (1,2,3)

P.S. I'm rewriting this explanation in the book to be even clearer.