2

How many objects are created when the below mentioned program is run in python 2.7.6? *I'm aware that an error message occurs after the execution and I'm also aware that strings are immutable and that's the reason behind the error message. What I really want to know is to find whether an object 's' is being created before the error or not?

string = "abcd"
string[1] = "s"

3 Answers 3

3

It is. A call string.__setitem__(1, "s") will be made. So, the string object has to exist to make the call. The call is BTW not guaranteed to fail. __setitem__ can be overridden and have nearly any behavior.

Sign up to request clarification or add additional context in comments.

Comments

1

In the code:

string = "abcd"

An immutable str object will be created from "abcd". The name string becomes a reference to that object, and the reference count is incremented. Note that there is a name in the standard library called string, and if you had imported it then that name will no longer refer to the module, but to "abcd".

string[1] = "s"

An immutable str object will be created from "s", but the assignment fails, so the reference count is not incremented. In theory that means it can be garbage collected, unless something else already references "s". In practice there are optimisation features that might not destroy the object at once, those are implementation dependant and should not be relied upon.

Comments

0

If you want to convince yourself that the object 's' is created beforehand (as explained in the other answers) you could use the walrus operator (available since Python 3.8):

IIn [4]: string = 'abcd'

In [5]: string[1] = (obj := 's')
Traceback (most recent call last):

  File "<ipython-input-5-3049f7ccfa62>", line 1, in <module>
    string[1] = (obj := 's')

TypeError: 'str' object does not support item assignment


In [6]: obj
Out[6]: 's'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.