[[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.
© 2025 OneMinuteCode. All rights reserved.