I changed only one element in the list, but the whole element changed. Why is that?

Asked 1 years ago, Updated 1 years ago, 107 views

[[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

2022-09-21 19:40

1 Answers

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.


2022-09-21 19:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.