How does python know?

Tobiah toby at tobiah.org
Wed Feb 12 21:27:00 CET 2014


On 02/12/2014 12:17 PM, Tobiah wrote:
> I do this:
>
> a = 'lasdfjlasdjflaksdjfl;akjsdf;kljasdl;kfjasl'
> b = 'lasdfjlasdjflaksdjfl;akjsdf;kljasdl;kfjasl'
>
> print
> print id(a)
> print id(b)
>
>
> And get this:
>
> True
> 140329184721376
> 140329184721376
>
>
> This works for longer strings.  Does python
> compare a new string to every other string
> I've made in order to determine whether it
> needs to create a new object?
>
> Thanks,
>
> Tobiah

Weird as well, is that in the interpreter,
the introduction of punctuation appears to
defeat the reuse of the object:

 >>> b = 'lasdfjlasdjflaksdjflakjsdfkljasdlkfjasl'
 >>> a = 'lasdfjlasdjflaksdjflakjsdfkljasdlkfjasl'
 >>> a is b
True
 >>> a = 'la;sdfjlasdjflaksdjflakjsdfkljasdlkfjasl'
 >>> b = 'la;sdfjlasdjflaksdjflakjsdfkljasdlkfjasl'
 >>> a is b
False
 >>> b = 'la.sdfjlasdjflaksdjflakjsdfkljasdlkfjasl'
 >>> a = 'la.sdfjlasdjflaksdjflakjsdfkljasdlkfjasl'
 >>> a is b
False
 >>> a = 'lasdfjlasdjflaksdjflakjsdfkljasdlkfjasl'
 >>> b = 'lasdfjlasdjflaksdjflakjsdfkljasdlkfjasl'
 >>> a is b
True

Tobiah



More information about the Python-list mailing list