Immutable vs Mutable types

前端 未结 16 1653
感情败类
感情败类 2020-11-21 05:51

I\'m confused on what an immutable type is. I know the float object is considered to be immutable, with this type of example from my book:

class         


        
16条回答
  •  攒了一身酷
    2020-11-21 06:36

    For immutable objects, assignment creates a new copy of values, for example.

    x=7
    y=x
    print(x,y)
    x=10 # so for immutable objects this creates a new copy so that it doesnot 
    #effect the value of y
    print(x,y)
    

    For mutable objects, the assignment doesn't create another copy of values. For example,

    x=[1,2,3,4]
    print(x)
    y=x #for immutable objects assignment doesn't create new copy 
    x[2]=5
    print(x,y) # both x&y holds the same list
    

提交回复
热议问题