Does Python have a pool of all strings and are they (strings) singletons there?
More precise, in the following code, are one or two strings created in memory?
a = str(num)
b = str(num)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Strings are immutable in Python, so the implementation can decide whether to intern (that’s a term often associated with C#, meaning that some strings are stored in a pool) strings or not.
In your example, you’re dynamically creating strings. CPython does not always look into the pool to detect whether the string is already there – it also doesn’t make sense because you first have to reserve memory in order to create the string, and then compare it to the pool content (inefficient for long strings).
But for strings of length 1, CPython does look into the pool (cf. “stringobject.c”):
So:
But when using constant strings directly in your code, CPython uses the same string instance: