Reputation: 47
I was playing with the following codes and found out that the string variables have same ids. Can anyone please tell me why only string acts differently unlike other two int and list type?
To sum up the question again, the number1 and number2 have different ids. list1 and list2 also have different ids. However, string1, string2 and even string3 have same ids with other string variables...!
number1 = 123456
number2 = 123456
number3 = number1
print(id(number1))
print(id(number2))
print(id(number3))
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print(id(list1))
print(id(list2))
print(id(list3))
string1 = 'hello'
string2 = 'hello'
string3 = string1
print(id(string1))
print(id(string2))
print(id(string3))
Upvotes: 2
Views: 251
Reputation: 226231
You've observed some of internal implementation details (optimizations that aren't guaranteed by the language):
Integers in the range -5 <= x <= 256
are pre-computed on startup and are reused.
Strings typed directly in your program string1 = 'hello'
are interned and reused.
There are also some guaranteed behaviors:
Assignments such as string3 = string1
never make copies.
New mutable objects are never reused: [1, 2, 3]
. They have have to be distinct so they can mutate differently over time.
Singletons such as None
are instantiated only once and can be reliably compared using object identity: result is None
.
Hope this provides you with some insights in to the language and its implementation.
Upvotes: 2