-1

This is a snippet of my code

    print (stats)
    print (mstats)
    stats[1] -= round(dam)
    print (mstats)
    print (stats)

stats is the list that should be edited but mstats is edited as well. I don't know why and was wondering how to stop mstats from changing.

This is what the code outputs:

['One', 142, 27, 0.025, 12, 2.3, 8, 14, '']
['One', 142, 27, 0.025, 12, 2.3, 8, 14, '']
['One', 133, 27, 0.025, 12, 2.3, 8, 14, '']
['One', 133, 27, 0.025, 12, 2.3, 8, 14, '']

The index [1] changes from 142 to 133 in both lists when it should only in one. Please can you help me? Thanks

lolol
  • 69
  • 11
  • for further reading: http://nedbatchelder.com/text/names1.html or for a brief summary, see my answer – Ilja Mar 15 '16 at 19:07

1 Answers1

2

Probably, it is the same list with two different names.

You can check it with

print(stats is mstats)

This is different from

print(stats == mstats)

The former shows you, that it's the same object, the latter checks the actual contents, which might be the same by coinsidence.

You probably wrote earlier something like

mstats = stats

to save you work to fill. This doesn't create a new list, but assigns the same old list a second name. Instead, you have to force to copy the list. For example (there are probably yet more options)

mstats = stats[:]

or

mstats = 1*stats

or

mstats = list(stats)

would do.

Ilja
  • 2,024
  • 12
  • 28
  • 1
    In my opinion, the most readable way to copy a list is this: `mstats = list(stats)` – arne.z Mar 15 '16 at 19:10
  • Thank you, you were correct. What does the colon in the first answer mean? (Please remind me in five minutes to tick your answer, I will probably forget.) – lolol Mar 15 '16 at 19:11
  • than yot, I edited it as a possibility – Ilja Mar 15 '16 at 19:11
  • the colon is a slicing index, like in `mylist[2:5]` - just that you leave out the start and stop, so the defaults are used, which slices the whole list. You can read more in the link in my comment to your question – Ilja Mar 15 '16 at 19:25