[[1, 1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1]] I wrote it like this.
myList = [[1] * 4] * 3
I changed only one value at the beginning, but the whole value of the element changed.
myList[0][0] = 5 #[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
Does anyone know why this happened? TT?
list python nested-list mutable
If [1,1,1,1]
is set to x, [x]*3
creates [x,x,x]
.
In other words, each element of [x]*3
is the same object, not just the same value.
myList = [[1] * 4] * 3
print(myList[1] is myList[2])
print(myList[1] is [1]*4)
print(myList[1] is [1,1,1,1])
Result:
True
False
False
To resolve this issue
mylist = [[1]*4 for n in range(3)]
You can change it to that.
610 GDB gets version error when attempting to debug with the Presense SDK (IDE)
578 Understanding How to Configure Google API Key
617 Uncaught (inpromise) Error on Electron: An object could not be cloned
912 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
© 2024 OneMinuteCode. All rights reserved.