From: Terry Reedy on 13 Aug 2010 01:12 On 8/12/2010 10:52 PM, Matt Schinckel wrote: >>>> a = "hello" >>>> b = "hello" >>>> a is b > True > > Ooh, that looks dangerous. Only for mutable objects > Are they the same object? Yes. >>>> a += "o" This is equivalent to a = a+"o". The expression creates a new object. The assignment binds the object to name 'a'. > (Python does not make two copies of small strings until it needs to). Python never copies *any* object until you ask it to. It never made a copy of the original 'a' here either. It combined the values of two string objects to make a new string object with a new value. -- Terry Jan Reedy
From: Steven D'Aprano on 13 Aug 2010 02:03
On Thu, 12 Aug 2010 19:52:07 -0700, Matt Schinckel wrote: >>>> a = "hello" >>>> b = "hello" >>>> a is b > True > > Ooh, that looks dangerous. Are they the same object? You don't need another test to know that they are the same object. The `is` operator does exactly that: a is b *only* if a and b are the same object. >>>> a += "o" >>>> a > 'helloo' >>>> b > 'hello' > > Phew. This tests for mutability, not sameness. If strings were mutable, then modifying a in place would likewise cause b to be modified (because they are the same object). Here's an example: >>> a = b = [1, 2, 3] >>> a is b True >>> a += [4] >>> b [1, 2, 3, 4] But of course, if strings were mutable like lists, they wouldn't be cached! The consequences would be horrific if they were, unless Python's execution model were radically different. Copy-on-write perhaps? > (Python does not make two copies of small strings until it needs to). Python doesn't copy anything unless you ask it to. -- Steven |