Immutable vs Mutable types

前端 未结 16 1656
感情败类
感情败类 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:26

    Difference between Mutable and Immutable objects

    Definitions

    Mutable object: Object that can be changed after creating it.
    Immutable object: Object that cannot be changed after creating it.

    In python if you change the value of the immutable object it will create a new object.

    Mutable Objects

    Here are the objects in Python that are of mutable type:

    1. list
    2. Dictionary
    3. Set
    4. bytearray
    5. user defined classes

    Immutable Objects

    Here are the objects in Python that are of immutable type:

    1. int
    2. float
    3. decimal
    4. complex
    5. bool
    6. string
    7. tuple
    8. range
    9. frozenset
    10. bytes

    Some Unanswered Questions

    Questions: Is string an immutable type?
    Answer: yes it is, but can you explain this: Proof 1:

    a = "Hello"
    a +=" World"
    print a
    

    Output

    "Hello World"
    

    In the above example the string got once created as "Hello" then changed to "Hello World". This implies that the string is of the mutable type. But it is not when we check its identity to see whether it is of a mutable type or not.

    a = "Hello"
    identity_a = id(a)
    a += " World"
    new_identity_a = id(a)
    if identity_a != new_identity_a:
        print "String is Immutable"
    

    Output

    String is Immutable
    

    Proof 2:

    a = "Hello World"
    a[0] = "M"
    

    Output

    TypeError 'str' object does not support item assignment
    

    Questions: Is Tuple an immutable type?
    Answer: yes, it is. Proof 1:

    tuple_a = (1,)
    tuple_a[0] = (2,)
    print a
    

    Output

    'tuple' object does not support item assignment
    

提交回复
热议问题