Sobes.tech
Junior — Middle

What does it mean that strings in Python are objects with immutable state?

sobes.tech AI

Answer from AI

In Python, strings are objects with immutable state, which means:

  • Once created, a string cannot be changed. Any operations that seem to modify the string actually create a new string.
  • This ensures safety and predictability when working with strings, especially when using them as keys in dictionaries or elements of a set.

Example:

s = "hello"
s = s + " world"  # a new string is created, the original 'hello' remains unchanged
print(s)  # 'hello world'

Here, s + " world" does not modify the original string but creates a new one.