1
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?

2 Answers2

6

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[:])
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
3

as Avinash mentioned, it's because you're still referring to the stats list. Meaning, changes made later (like the removal of an item) will still be reflected. For the expected behaviour, you can make a copy of the list like so:

newCopy = list(stats)
rollslist.append(newCopy)
Community
  • 1
  • 1
Huey
  • 5,110
  • 6
  • 32
  • 44