Immutable type identifier

I am a little confused by the difference between mutable and immutable objects. I tried the following code snippet to find the id of the objects:

tuple1 = ('Object1', 'Object2')
print id(tuple1)
tuple2 = ('Object1', 'Object2')
print id(tuple2)
list1 = ['Object1', 'Object2']
print id(list1)
list2 = ['Object1', 'Object2']
print id(list2)
string1 = "Foo bar"
print id(string1)
string2 = "Foo bar"
print id(string2)

I got the same identifier for strings and a different identifier for lists, but a different identifier for tuples. Don't they have the same identifier? I was wondering if anyone can explain how this works?

thank

+3
source share
4 answers

The same identifiers mean the same object, but the Python implementation allows you to optimize the creation of immutable objects as you see fit. For example, in CPython 2.6.6, small integer objects are cached, so:

>>> x=256
>>> x is 256
True
>>> x=1024
>>> x is 1024
False

[NOTE: 'is' tests for object identity (same ID)]

, . , ? , , , , , , , , , .

== , ID.

+4

, . , .

, , (: ), , , . , .

+3

Immatable means you cannot change an instance of a class. For instance:

salad = ["Lettuce","Tomato","Onion","Tuna"]
fruit = ("Apple","Banana","Cherry","Fig","Grapefruit")
salad[3] = "Cheese"   # works
fruit[3] = "Orange"   # error message
+1
source

By default, the interpreter creates only one common object for small integers or strings.

+1
source

Source: https://habr.com/ru/post/1777215/


All Articles