简体   繁体   中英

Python strings immutable?

Python strings are supposed to be immmutable just like integers. Consider this:

>>> num1 = 34
>>> num2 = 36
>>> id(num1)
505894832
>>> num4 = 34
>>> id(num4)
505894832

num4 has the exact same ID as num1, which means they are pointing to the same thing. Shouldn't the same thing happen with strings ? Am confused with:

>>> name = "Sumeet"
>>> id(name)
35692000
>>> name = "Ali"
>>> id(name)
35926912
>>> naam = "Sumeet"
>>> id(naam)
35926848

Shouldn't the last output be: 35692000 ?

The fact that several variables have the same id has nothing much to do with the actual objects being immutable.

In fact, this can happen safely (saving memory), due to their immutability.

Let's assume that a string in python was not immutable, you declared:

a = 'abc'

b = 'abc'

If you changed a , that would mean that b would either reference a completely different object (duplicating the memory needed to represent the same literal string), or that, when a was changed, the whole object would have to be copied over in order to make the change (so that b wouldn't be affected).

Since the strings are immutable, both variables can safely point to the same object. Any change to an immutable data structure creates a new structure, and the reference that was pointing towards it is changed to the new one, leaving all other references to the "old" structure unchanged. The absence of side effects in immutable data structures greatly diminishes the possibility of errors occurring due to a shared structure/object being changed somewhere else in your code.

CPython interns some very small integers and very small strings, but you can't rely on this since it's implementation dependent.

So, here are some counterexamples to your findings:

>>> a = 123456
>>> b = 123456
>>> id(a)
30497296
>>> id(b)
30496144
>>> a = "hey"
>>> b = "hey"
>>> id(a)
44067112
>>> id(b)
44067112

No it doesn't point to the same thing, for one clear and concise reason.

When you do this:

name = 'Sumeet'

You essentially create a new string object and bind it to the name reference. When you do this:

naam = 'Sumeet'

You are again creating a NEW string object and bind it to the naam reference. In order for them to point to the same object, you should have done this:

naam = name

This makes naam refer to the same object that name refers to.


Regarding the integers, the CPython implementation of Python has a feature that caches small integers. For instance, according to this source python 3.2 caches integer objects from -5 to 256 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM