If you happen to’ve ever been curious why some strings in Python seem to share the identical reminiscence tackle, or puzzled about Python’s mysterious string interning, you’re in the suitable place.
This submit explains:
- What string interning is
- Why Python makes use of it
- When and the way it occurs
- The way it impacts your applications
- Find out how to use it successfully
String interning is a technique Python makes use of to retailer just one copy of sure immutable strings, reusing the identical reminiscence tackle for similar strings to save lots of reminiscence and enhance efficiency.
In different phrases:
As an alternative of storing two separate however similar strings, Python retains only one copy and makes variables level to that very same object.
Python strings are immutable — which means they can’t be modified after creation. This makes interning protected as a result of sharing the identical string object received’t trigger surprising modifications.
Advantages of interning:
- Saves reminiscence when the identical string seems a number of occasions