Search code examples
pythonlistappend

Unexpected list append


import random
stats = []
statslist = []
rollslist = []
for 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 it to print four numbers for the fourth result instead of the three it's giving me. I appended the list before the number was removed. What am I missing?


Solution

  • You added a mutable list. When you modified it later, the modification affected the object you placed in the list, because it was a direct reference and not a copy.

    The easiest way to make a copy of a list is to use slicing:

    rollslist.append(stats[:])