string slicing

Kent Johnson kent3737 at yahoo.com
Sun Dec 5 15:44:13 CET 2004


Ishwor wrote:
>>>>s = 'hello'
>>>>m = s[:]
>>>>m is s
> 
> True
> 
>  I discussed the *is* operator with some of the pythoners before as
> well but it is somewhat different than what i intended it to do. The
> LP2E by Mark & David says -
> " m gets a *full top-level copy* of a sequence object- an object with
> the same value but distinct piece of memory." but when i test them
> with *is* operator then the result is True. Why is this happening??

This behaviour is due to the way strings are handled. In some cases strings are 'interned' which 
lets the interpreter keep only a single copy of a string. If you try it with a list you get a 
different result:

 >>> s=list('hello')
 >>> s
['h', 'e', 'l', 'l', 'o']
 >>> m=s[:]
 >>> m
['h', 'e', 'l', 'l', 'o']
 >>> m is s
False

Kent



More information about the Python-list mailing list