python - Unexpected list append -
import random stats = [] statslist = [] rollslist = [] var1 in range(4): stats.append(random.randrange(1, 7)) rollslist.append(stats) print(stats) b = min(stats) stats.remove(b) print(sum(stats)) statslist.append(sum(stats)) print(stats) print(rollslist) print(statslist)
actual result
[5, 1, 1, 3] 9 [5, 1, 3] [[5, 1, 3]] [9]
expected result
[5, 1, 1, 3] 9 [5, 1, 3] [[5, 1, 1, 3]] [9]
i'm expecting print 4 numbers fourth result instead of 3 it's giving me. appended list before number removed. missing?
you added mutable list. when modified later, modification affected object placed in list, because direct reference , not copy.
the easiest way make copy of list use slicing:
rollslist.append(stats[:])
Comments
Post a Comment