Why are lists linked in Python in a persistent way? -
a variable set. variable set first. first changes value. second not. has been nature of programming since dawn of time.
>>> = 1 >>> b = >>> b = b - 1 >>> b 0 >>> 1 i extend python lists. list declared , appended. list declared equal first. values in second list change. mysteriously, values in first list, though not acted upon directly, change.
>>> alist = list() >>> blist = list() >>> alist.append(1) >>> alist.append(2) >>> alist [1, 2] >>> blist [] >>> blist = alist >>> alist.remove(1) >>> alist [2] >>> blist [2] >>> why this?
and how prevent happening -- want alist unfazed changes blist (immutable, if will)?
variable binding in python works way: assign object variable.
a = 4 b = both point 4.
b = 9 now b points somewhere else.
exactly same happens lists:
a = [] b = b = [9] now, b has new value, while a has old one.
till now, clear , have same behaviour mutable , immutable objects.
now comes misunderstanding: modifying objects.
lists mutable, if mutate list, modifications visible via variables ("name bindings") exist:
a = [] b = # same list c = [] # empty 1 a.append(3) print a, b, c # b = [3], c = [] different 1 d = a[:] # copy b.append(9) # = b = [3, 9], c = [], d = [3], copy of old resp. b
Comments
Post a Comment