Search code examples
pythonvariable-assignmentimmutabilitymutable

The immutable object in python


I see a article about the immutable object.

It says when:
variable = immutable
As assign the immutable to a variable.

for example
a = b # b is a immutable
It says in this case a refers to a copy of b, not reference to b. If b is mutable, the a wiil be a reference to b

so:

a = 10
b = a
a =20
print (b) #b still is 10

but in this case:

a = 10
b = 10
a is b # return True
print id(10)
print id(a)
print id(b) # id(a) == id(b) == id(10)

if a is the copy of 10, and b is also the copy of 10, why id(a) == id(b) == id(10)?


Solution

  • While that article may be correct for some languages, it's wrong for Python.

    When you do any normal assignment in Python:

    some_name = some_name_or_object
    

    You aren't making a copy of anything. You're just pointing the name at the object on the right side of the assignment.

    Mutability is irrelevant.

    More specifically, the reason:

    a = 10
    b = 10
    a is b
    

    is True, is that 10 is interned -- meaning Python keeps one 10 in memory, and anything that is set to 10 points to that same 10.

    If you do

    a = object()
    b = object()
    a is b
    

    You'll get False, but

    a = object()
    b = a
    a is b
    

    will still be True.