Immutable vs Mutable types

前端 未结 16 1685
感情败类
感情败类 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
    
    0 讨论(0)
  • 2020-11-21 06:37

    You have to understand that Python represents all its data as objects. Some of these objects like lists and dictionaries are mutable, meaning you can change their content without changing their identity. Other objects like integers, floats, strings and tuples are objects that can not be changed. An easy way to understand that is if you have a look at an objects ID.

    Below you see a string that is immutable. You can not change its content. It will raise a TypeError if you try to change it. Also, if we assign new content, a new object is created instead of the contents being modified.

    >>> s = "abc"
    >>>id(s)
    4702124
    >>> s[0] 
    'a'
    >>> s[0] = "o"
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'str' object does not support item assignment
    >>> s = "xyz"
    >>>id(s)
    4800100
    >>> s += "uvw"
    >>>id(s)
    4800500
    

    You can do that with a list and it will not change the objects identity

    >>> i = [1,2,3]
    >>>id(i)
    2146718700
    >>> i[0] 
    1
    >>> i[0] = 7
    >>> id(i)
    2146718700
    

    To read more about Python's data model you could have a look at the Python language reference:

    • Python 2 datamodel
    • Python 3 datamodel
    0 讨论(0)
  • 2020-11-21 06:39

    What? Floats are immutable? But can't I do

    x = 5.0
    x += 7.0
    print x # 12.0
    

    Doesn't that "mut" x?

    Well you agree strings are immutable right? But you can do the same thing.

    s = 'foo'
    s += 'bar'
    print s # foobar
    

    The value of the variable changes, but it changes by changing what the variable refers to. A mutable type can change that way, and it can also change "in place".

    Here is the difference.

    x = something # immutable type
    print x
    func(x)
    print x # prints the same thing
    
    x = something # mutable type
    print x
    func(x)
    print x # might print something different
    
    x = something # immutable type
    y = x
    print x
    # some statement that operates on y
    print x # prints the same thing
    
    x = something # mutable type
    y = x
    print x
    # some statement that operates on y
    print x # might print something different
    

    Concrete examples

    x = 'foo'
    y = x
    print x # foo
    y += 'bar'
    print x # foo
    
    x = [1, 2, 3]
    y = x
    print x # [1, 2, 3]
    y += [3, 2, 1]
    print x # [1, 2, 3, 3, 2, 1]
    
    def func(val):
        val += 'bar'
    
    x = 'foo'
    print x # foo
    func(x)
    print x # foo
    
    def func(val):
        val += [3, 2, 1]
    
    x = [1, 2, 3]
    print x # [1, 2, 3]
    func(x)
    print x # [1, 2, 3, 3, 2, 1]
    
    0 讨论(0)
  • 2020-11-21 06:39

    I haven't read all the answers, but the selected answer is not correct and I think the author has an idea that being able to reassign a variable means that whatever datatype is mutable. That is not the case. Mutability has to do with passing by reference rather than passing by value.

    Lets say you created a List

    a = [1,2]
    

    If you were to say:

    b = a
    b[1] = 3
    

    Even though you reassigned a value on B, it will also reassign the value on a. Its because when you assign "b = a". You are passing the "Reference" to the object rather than a copy of the value. This is not the case with strings, floats etc. This makes list, dictionaries and the likes mutable, but booleans, floats etc immutable.

    0 讨论(0)
  • 2020-11-21 06:41

    The simplest answer:

    A mutable variable is one whose value may change in place, whereas in an immutable variable change of value will not happen in place. Modifying an immutable variable will rebuild the same variable.

    Example:

    >>>x = 5
    

    Will create a value 5 referenced by x

    x -> 5

    >>>y = x
    

    This statement will make y refer to 5 of x

    x -------------> 5 <-----------y

    >>>x = x + y
    

    As x being an integer (immutable type) has been rebuild.

    In the statement, the expression on RHS will result into value 10 and when this is assigned to LHS (x), x will rebuild to 10. So now

    x--------->10

    y--------->5

    0 讨论(0)
  • 2020-11-21 06:44

    Whether an object is mutable or not depends on its type. This doesn't depend on whether or not it has certain methods, nor on the structure of the class hierarchy.

    User-defined types (i.e. classes) are generally mutable. There are some exceptions, such as simple sub-classes of an immutable type. Other immutable types include some built-in types such as int, float, tuple and str, as well as some Python classes implemented in C.

    A general explanation from the "Data Model" chapter in the Python Language Reference":

    The value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable.

    (The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.)

    An object’s mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.

    0 讨论(0)
提交回复
热议问题