-1

enter image description here

When I assign to an element in 3d python list, it will change 3 element.

Does anyone know what happened?

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
Chaos
  • 21
  • 5
  • When you say [[[0,0]]*4], that doesn't create a list referring to four different lists. That creates a list containing 4 references to a SINGLE list. There is one [0,0] list object, The easiest way to do what you want doing is to use `numpy`. Short of that, you'll need to use nested loops. – Tim Roberts May 12 '21 at 02:59
  • Thanks a lot, I should go deeper to python. – Chaos May 12 '21 at 03:10

1 Answers1

1

Yep, It has to do with the underlying way in which arrays are stored in Python. When you created your array initially, with the [[0,0]]*4, you created four pointers to the same list(you did that four separate times, hence why 1/4 of your lists were changed). Thus, when you change 1 value, it changes it in that one list, but there are multiple pointers to the same list, so it appears to change multiple values. I highly recommend http://pythontutor.com/ for visualizing how your code is executed/the underlying structures at play.

Brian
  • 56
  • 3