python - Item assignment in a nested list -
i'm trying change item in nested list. thought straightforward. have following:
temp = [1, 2, 3, 4] my_list = [temp in xrange(4)] print "my_list = ", my_list out: my_list = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
so normal list of lists. want access 1 item:
print my_list[0][1] out: 2
as expected. problem comes when changing item. want change item in my_list[0][1], following:
my_list[0][1]= "a" print my_list out: [[1, 'a', 3, 4], [1, 'a', 3, 4], [1, 'a', 3, 4], [1, 'a', 3, 4]]
why changing 4 positions, instead of one? how avoid it?
since lists mutable objects when repeat list inside 1 made list of same objects (all of them point 1 memory address),for getting rid of problem need copy nested lists in each iteration :
>>> temp = [1, 2, 3, 4] >>> my_list = [temp[:] in xrange(4)] >>> my_list[0][1]= "a" >>> print my_list [[1, 'a', 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]] >>>
Comments
Post a Comment