If strings are immutable, how do we add one string to another?


#1

Question

If strings in Python are immutable, how do we add one string to another? Wouldn’t this update the string?

Answer

When concatenating two strings in Python, rather than updating a string, it creates an entirely new string in memory.

What basically happens is, first, space in computer memory is allocated to fit the two strings. Then, the first string is copied, followed by the second string. This new string is an entirely new string value from the original two.

Example

# When concatenating these strings, the string “John”
# doesn’t actually change. 
# Rather, space is created for the combined string, 
# both strings will be copied into that space, and then
# the variable will be updated to this new string.

name = "John"
name += " Doe"
# name is now "John Doe"