search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

0 answers
Q&A About the changing id of an immutable string
About the changing id of an immutable string
P粉071602406 2026-01-04 12:22:12 Views 105

0

Something about the id of objects of type str (in python 2.7) puzzles me. The str type is immutable, so I would expect that once it is created, it will always have the same id. I believe I don't phrase myself so well, so instead I'll post an example of input and output sequence.

>>> id('so')
140614155123888
>>> id('so')
140614155123848
>>> id('so')
140614155123808

so in the meanwhile, it changes all the time. However, after having a variable pointing at that string, things change:

>>> so = 'so'
>>> id('so')
140614155123728
>>> so = 'so'
>>> id(so)
140614155123728
>>> not_so = 'so'
>>> id(not_so)
140614155123728

So it looks like it freezes the id, once a variable holds that value. Indeed, after del so and del not_so, the output of id('so') start changing again.

This is not the same behaviour as with (small) integers.

I know there is not real connection between immutability and having the same id; still, I am trying to figure out the source of this behaviour. I believe that someone whose familiar with python's internals would be less surprised than me, so I am trying to reach the same point...

Update

Trying the same with a different string gave different results...

>>> id('hello')
139978087896384
>>> id('hello')
139978087896384
>>> id('hello')
139978087896384

Now it is equal...

Your Answer
submit

0 answers

Popular tool

vc9-vc14 (32+64 bit) runtime library collection (link below)

vc9-vc14 (32+64 bit) runtime library collection (link below)

Download the collection of runtime libraries required for phpStudy installation

VC9 32-bit

VC9 32-bit

VC9 32-bit phpstudy integrated installation environment runtime library

PHP programmer toolbox full version

PHP programmer toolbox full version

Programmer Toolbox v1.0 PHP Integrated Environment

VC11 32-bit

VC11 32-bit

VC11 32-bit phpstudy integrated installation environment runtime library

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use