Does assigning another variable to a string make a copy or increase the reference count

Viewed 7997

On p.35 of "Python Essential Reference" by David Beazley, he first states:

For immutable data such as strings, the interpreter aggressively shares objects between different parts of the program.

However, later on the same page, he states

For immutable objects such as numbers and strings, this assignment effectively creates a copy.

But isn't this a contradiction? On one hand he is saying that they are shared, but then he says they are copied.

3 Answers

No, assigning a pre-existing str variable to a new variable name does not create an independent copy of the value in memory.

The existence of unique objects in memory can be checked using the id() function. For example, using the interactive Python prompt, try:

>>> str1 = 'ATG'
>>> str2 = str1

Both str1 and str2 have the same value:

>>> str1
'ATG'
>>> str2
'ATG'

This is because str1 and str2 both point to the same object, evidenced by the fact that they share the same unique object ID:

>>> id(str1)
140439014052080
>>> id(str2)
140439014052080
>>> id(str1) == id(str2)
True

Now suppose you modify str1:

>>> str1 += 'TAG'  # same as str1 = str1 + 'TAG'
>>> str1
ATGTAG

Because str objects are immutable, the above assignment created a new unique object with its own ID:

>>> id(str1)
140439016777456
>>> id(str1) == id(str2)
False

However, str2 maintains the same ID it had earlier:

>>> id(str2)
140439014052080

Thus, execution of str1 += 'TAG' assigned a brand new str object with its own unique ID to the variable str1, while str2 continues to point to the original str object.

This implies that assigning an existing str variable to another variable name does not create a copy of its value in memory.

Related