0

Why does it change ALL the 3rd elements in the list?

https://code.sololearn.com/cSJFvZo6ntPQ/?ref=app

22nd Feb 2020, 7:15 PM
Blabla Blablabla
5 Answers
+ 1
I also don't fully understand what your plan is, but I'll make a guess about the problem. gameboard = [snsa for i in range(inputt)] That line puts the list snsa into gameboard. Not a copy of the list, but THE list. snsa is like an adress card to the actual list, and when you access it, you actually say: 'Please go to the list snsa.' So when you change one, you'll change them all - because in reality it is only ONE list. What you need to do instead: Fill your board with *copies* of snsa. Quickest way to do it: gameboard = [snsa[:] for i in range(inputt)]
22nd Feb 2020, 9:47 PM
HonFu
HonFu - avatar
+ 4
You can easily check if some objects have the same references/addresses by printing the ids. Like print(id(gameboard)) Useful for debugging.
22nd Feb 2020, 11:17 PM
Matthias
Matthias - avatar
+ 2
Thanks HonFu Youre awesome! That's exactly what I needed!
22nd Feb 2020, 9:56 PM
Blabla Blablabla
+ 1
Hello Blabla Blablabla Can you explain what you are trying to achieve? Maybe it helps to add an example with input and expected output.
22nd Feb 2020, 7:57 PM
Denise Roßberg
Denise Roßberg - avatar
0
It's an issue that will accompany you for a long time, especially in Python. Even after practicing for about two years, this happens to me (although I foresee (rather dread) it more often). Whenever something freaky happens in one of my codes, first thing I ask myself: Alright, where do I have reference trouble? Where am I accessing the very same item instead of copying?
22nd Feb 2020, 10:08 PM
HonFu
HonFu - avatar