user user - 4 months ago 10
Python Question

Why both lists get modified after calling append() function on only one in python?

So I am learning python these days and got stuck on a problem. Here is my code.

a = [1, 2, 3, 4, 5]
b = a
print(a)
print(b)
b.append(8)
print(a)
print(b)


The output is as follows.

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 8]
[1, 2, 3, 4, 5, 8]


Why do both lists get modified even when I call it on only b? When we assign b = a, aren't we making a separate copy of that list?

2ps 2ps
Answer

Because python uses references for arrays, objects, etc. If you want a copy of the array use copy:

import copy
b = copy.copy(a)
Comments