Martin McBride
1 min readMar 4, 2024

--

"So modifying a string’s value inside the function will create a new string object, but modifying a list is done directly on the original list, no new list will be created."

That's just wrong. You are confusing two concepts - the calling mechanism, and an object's mutability.

In the first example, initially `val` holds a reference to 'Yang Zhou'. Within the function, you assign a different string to the variable `val`, so it no longer holds the original string. That is nothing to do strings being immutable, it is simply that you have reassigned the variable.

In the second example, `val` holds a list. Within the function you operate on the list using `val.append()`. The reason Python uses the same list isn't because lists are mutable. It is because you told Python to append a value to the existing list.

In the second example, if you had passed a tuple into the function, Python would try to append a value to the tuple, which it can't do, as tuples are immutable. Python wouldn't automatically create a new tuple (that would be crazy). It throws an exception.

--

--

Martin McBride
Martin McBride

Responses (1)