Immutable vs Mutable types

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

    Common immutable type:

    1. numbers: int(), float(), complex()
    2. immutable sequences: str(), tuple(), frozenset(), bytes()

    Common mutable type (almost everything else):

    1. mutable sequences: list(), bytearray()
    2. set type: set()
    3. mapping type: dict()
    4. classes, class instances
    5. etc.

    One trick to quickly test if a type is mutable or not, is to use id() built-in function.

    Examples, using on integer,

    >>> i = 1
    >>> id(i)
    ***704
    >>> i += 1
    >>> i
    2
    >>> id(i)
    ***736 (different from ***704)
    

    using on list,

    >>> a = [1]
    >>> id(a)
    ***416
    >>> a.append(2)
    >>> a
    [1, 2]
    >>> id(a)
    ***416 (same with the above id)
    

提交回复
热议问题