Home > Back-end >  Python Immutability List in Tuple - Object or Value?
Python Immutability List in Tuple - Object or Value?

Time:02-08

Can someone help me understand why the second comparison between z and c variables resolve as False?

t = [1, 2, 3]
h = t
print(id(h), " ", id(t))
print(h is t)

x = ('bla', t)
y = ('bla', t)

z, c = str(x[1]), str(y[1])

print(id(z), " ", id(c))
print(z is c)

My initial impression is that x[1] and y[1] would be pointing to the same reference since we're directly assigning that index of the tuples to the t variable. Does this mean Python is passing in the value of t rather than the object of the variable? Why does h is t evaluate to True but z is c evaluate to false? *** scratches head ***

CodePudding user response:

This has nothing to do with tuples themselves, but with str being applied to basically anything that is not already a string (unless a class redefines its __str__ method to cache results):

x = 0

x is x
# True

str(x) is str(x)
# => False

This is because str(x) converts its argument into a new string each time.

Consequently, z and c in your example are different strings that happen to have the same content ('[1, 2, 3]').

CodePudding user response:

Immutability of a string is a necessary but not sufficient condition for having identical strings share the same object. There is some overhead in looking up a string to see if it already exists, so most of the time Python doesn't bother. It does provide a facility for interned strings so you can do it yourself if you want.

>>> import sys
>>> str(0) is str(0)
False
>>> sys.intern(str(0)) is sys.intern(str(0))
True
  •  Tags:  
  • Related