when do two names cease to refer to the same string object?
John Salerno
johnjsal at NOSPAMgmail.com
Thu Mar 2 20:45:10 EST 2006
To test this out a wrote a little script as an exercise:
for num in range(1, 10):
x = 'c' * num
y = 'c' * num
if x is y:
print 'x and y are the same object with', num, 'characters'
else:
print 'x and y are not the same object at', num, 'characters'
break
But a few questions arise:
1. As it is above, I get the 'not the same object' message at 2
characters. But doesn't Python only create one instance of small strings
and use them in multiple references? Why would a two character string
not pass the if test?
2. If I say x = y = 'c' * num instead of the above, the if test always
returns true. Does that mean that when you do a compound assignment like
that, it's not just setting each variable to the same value, but setting
them to each other?
Finally, I'd like to see how others might write a script to do this
exercise. Basically I just wanted to see when two names stop referring
to the same string, which I figured was based on length of the string.
But I've also noticed that putting spaces in the string also affects
things, so maybe there isn't just one way to test this.
More information about the Python-list
mailing list