python - Cannot modify item of list within for loop -
i've found out while executing for loop on list of mutable items cannot modify item, able modify element of item if element mutable. why?
# create alist contain mutable alist = [[1, 2, 3],] #1 loop x in alist: x = x + [9,] print alist # let's replace alist[0] list contain 1 , try modify alist[0] = [[[1,2],3]] print2 alist # [[[[1, 2], 3]]] #2 loop x in alist: x[0] = x[0] + [9,] # list modified ... print alist # [[[[1, 2], 3, 9]]], modified ! i aware modifying list iterating on isn't practice (it's better iterate on copy of it), please don't point me moment.
the reason of such behaviour while performing for loop #1 new list produced applying + operator list( can tracked getting id of x).
however in for loop #2 access element of item index x[0] object in memory being modified. can found calling id on x while iterating on alist
# create alist contain mutable alist = [[1, 2, 3],] #1 loop x in alist: print id(x), id(alist[0]), 'same?:', id(x) == id(alist[0]) # id(x): 4425690360 id(alist[0]) 4425690360 same?: true x = x + [9,] print id(x), id(alist[0]), 'same?:', id(x) == id(alist[0]) # id(x): 4425770696 id(alist[0]) 4425690360 same?: false # mutable item not modified, guess x copy of item print alist # [[1, 2, 3]] # let's replace alist[0] list contain 1 , try modify alist[0] = [[[1,2],3]] print alist #2 loop x in alist: print id(x), id(alist[0]), 'same?:', id(x) == id(alist[0]) # id(x): 4425811008 id(alist[0]) 4425811008 same?: true x[0] = x[0] + [9,] print id(x), id(alist[0]), 'same?:', id(x) == id(alist[0]) # id(x): 4425811008 id(alist[0]) 4425811008 same?: true # list modified ... print alist # [[[[1, 2], 3, 9]]] to solve problem use array.append modify item within loop, see sample below:
alist = [[1, 2, 3],] x in alist: print id(x), id(alist[0]), 'same?:', id(x) == id(alist[0]) x.append(9) print id(x), id(alist[0]), 'same?:', id(x) == id(alist[0]) # list modified ... print alist # [[1, 2, 3, 9],]
Comments
Post a Comment