Iam a beginer in python.Iam trying to add an array in a list but when i update that array and again append it to the list the previous appended array is also updated.Why is it happening?
list_of_sol=[]
a=[]
a.append(1)
list_of_sol.append(a)
a.append(2)
list_of_sol.append(a)
print list_of_sol
Output i was expecting was [[1],[1,2]] but output is [[1,2],[1,2]].
You are appending references to the list object a
. This can be verified via id()
of the two elements of the list.
>>> id(list_of_sol[1])
# 140477592091464
>>> id(list_of_sol[0])
# 140477592091464
So you end up appending two instances of a single object, rather than bare values. The expected behaviour can be realised using list_of_sol.append(list(a))
If you want the output you've said you expected, do it like this:
list_of_sol=[]
a=[]
a.append(1)
list_of_sol.append(a[:])
a.append(2)
list_of_sol.append(a)
print list_of_sol
This may be about copy and deepcopy: list_of_sol.append(a) puts a copy of a in list_of_sol, and this copy list_of_sol[0] refer to the same place with a, you can use id(list_of_sol[0]) == id(a) test it You can check this :
from copy import deepcopy
list_of_sol=[]
a=[]
a.append(1)
list_of_sol.append(deepcopy(a[:])) #here changed
a.append(2)
list_of_sol.append(deepcopy(a)) #here changed
print list_of_sol
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.