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


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


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.


# 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"

Maybe the lessons will touch on this later, but if strings are immutable do we need to worry about memory? How does Python handle garbage collection?


This bit of information is confusing for beginners


If a new string is created when concatenating “John” and “Doe”, we can still find the old name (“John”) somewhere in the memory, i.e. the old string value is not erased because of the concatenation?

This is where the garbage collection (mentioned by @beta6137346027) comes in. Give the string is no longer used, python gives the memory back to the operating system.

so maybe it will linger around in memory for a while, but we can no longer access it

then you would need to create new variable:

full_name = name + "Doe"

now we can still access name