My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

In Python, why does concatenating a list to another one creates another object in memory, whereas other manipulations induce mutation of the original object in memory?

David Lamorlette's photo
David Lamorlette
·Jul 19, 2017

*CASE A :

list=[0, 1, 2, 3]

list_copy=list

list=list+[4]

print(“list is ”,list)

print(“list_copy is “, list_copy)

—————

Print output :

list is [0, 1, 2, 3, 4]

list_copy is [0, 1, 2, 3]

—————

(this non-mutating behavior also happens when concatenating a list of more than a single entry, and when 'multiplying' the list, e.g. list=list*2)

In this case the original list object that “list” pointed to has not been altered in memory and list_copy still points to it, another object has simply been created in memory for the result of the concatenation that “list” now points to (there are now two distinct, different list objects in memory)

———————————————

*CASE B:

list=[0, 1, 2, 3]

list_copy=list

list.append(4)

print("list is ", list)

print("list_copy is ", list_copy)

——————

Outputs :

list is [0, 1, 2, 3, 4]

list_copy is [0, 1, 2, 3, 4]

____________________________

*CASE C:

list=[0, 1, 2, 3]

list_copy=list

list[-1]="foo"

print("list is ", list)

print("list_copy is ", list_copy)

—————————————

Outputs :

list is [0, 1, 2, 'foo']

list_copy is [0, 1, 2, 'foo']

—————————————

In case B and C the original list object that “list” points to has mutated, list_copy still points to that same object, and as a result the value of list_copy has changed. (there is still one single list object in memory and it has mutated).

This behavior seems inconsistent to me as a noob. Is there a good reason/utility for this?