Open In App

String Interning in Python

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

String interning is a memory optimization technique used in Python to enhance the efficiency of string handling. In Python, strings are immutable, meaning their values cannot be changed after creation. String interning, or interning strings, involves reusing existing string objects rather than creating new ones with the same value. This process can lead to memory savings and improved performance in certain scenarios.

Ways For String Interning in Python

Below, are the example of String Interning in Python.

String Interning Using Identical String Values

In this example, both str1 and str2 have the same value, “hello”. String interning ensures that identical string literals refer to the same memory location, making the is operator return True.

Python3




str1 = "hello"
str2 = "hello"
 
print(str1 is str2) 


Output

True



String Interning by String Concatenation

When concatenating strings using the + operator, Python automatically interns the resulting string if the concatenated values are string literals. This is a subtle optimization that enhances performance.

Python3




str1 = "hello"
str2 = "world"
concatenated_str = str1 + str2
 
print(concatenated_str is "helloworld"


Output

False



String Interning by String Slicing

String slices also benefit from interning. The resulting substring shares memory with the original string, reducing the overall memory footprint.

Python3




str1 = "python"
substring = str1[1:4]
 
print(substring is "yth"


Output

False



String Interning Using Explicit Interning

Python provides the intern() function to explicitly intern strings. In this example, both str1 and str2 reference the same interned string, ensuring that their memory locations are identical.

Python3




import sys
 
str1 = "apple"
str2 = sys.intern("apple")
 
print(str1 is str2)


Output

True



String Interning by Dictionary Keys

When using string literals as dictionary keys, Python automatically interns the keys. This behavior ensures efficient dictionary lookups and conserves memory by reusing string objects.

Python3




dictionary = {"key1": "value1", "key2": "value2"}
key_literal = "key1"
 
print(key_literal is "key1"
print(dictionary[key_literal]) 


Output

True
value1



Conclusion

Understanding string interning in Python is crucial for optimizing memory usage and improving the performance of string operations. By recognizing scenarios where interning occurs automatically and leveraging explicit interning when necessary, developers can write more memory-efficient code.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads