3

Consider the following:

var1 = 'test test'
var2 = 'test test'

list1=[10,12,12,"Test"]

list2=[10,12,12,"Test"]

print(id(var1) == id(var2)) # True
print(id(list1) == id(list2)) # False

This Boolean expression gives False. That means memory location of list1 and list2 are different. Why do variables with the same value point to the same memory location, while lists point different locations?

Lord Elrond
  • 13,430
  • 7
  • 40
  • 80

3 Answers3

6

Lists are mutable. You don't want changes to one ostensibly independent list modifying another that is coincidentally identical.

Strings, on the other hand, are immutable. You can't make changes to var1 that would affect var2, so it's possible to share the underlying object. Note that it is not guaranteed that two str literals produce the same object, though. It is implementation-dependent when and whether such caching occurs.

chepner
  • 497,756
  • 71
  • 530
  • 681
2

The fact that variables with the same value have the same id is an artifact of the underlying implementation. For example, small integers are interned; as are common strings and those which appear as identifies. The advantage here is that - as strings and integers are immutable - every use can refer to the same memory location, reducing memory consumption.

However, not all "equal" values are "identical". The two lists as mentioned in your question are independent from one another. It is infeasible to detect if two objects happen to be equal, just in order to gain a small memory-saving, and having to separate them once they become un-equal.

It is a common source of confusion the see string comparisons as in foo is "bar" instead of foo == "bar". It seems to work on CPython, if "bar" has been interned. The comparison will always be false on other interpreters, though,

user2722968
  • 13,636
  • 2
  • 46
  • 67
2

Since strings are immutable in Python, it doesn't make a difference if the objects are the same or not - sharing the objects is an optimization applied by Python. It can't do that for lists since those can be modified.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622