string slicing

I

Ishwor

Hello all ,
I am trying some interactive examples here where i have come across
inconsistencies??? :O
Anyway heres whats bothering me
s = 'hello'
s[0] 'h'
s[:] 'hello'
m = s[:]
m 'hello'
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??
Any help is appreciated.. Thanx
 
K

Kent Johnson

Ishwor said:
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
 
I

Ishwor

[snip]
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

Thanx Kent. so for lists Python doesn't keep the same object in the
cache??? So in that case it is not interned & hence any objects
created will **point** to seperate area in memory as seen by your
Thanx again :)
[snip]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
474,213
Messages
2,571,105
Members
47,698
Latest member
TerraT521

Latest Threads

Top