I find when repeating an element to a list, people use [elem] * n
. But when repeating a list to a list, people use [[list] for _ in range(n)]
, instead of [[list]] * n
. I see comments saying that the latter will cause a problem due to "mutable" feature of a list, and I can see the result of the problem in my code. Can anybody explain what problem this method will cause, and what might be the consequence?
Asked
Active
Viewed 19 times
0

Xiaoying
- 1
-
[The accepted answer](https://stackoverflow.com/a/240205/15497888) goes through why this happens in detail. [The question itself](https://stackoverflow.com/q/240178/15497888) outlines one of the consequences of having multiple references to the same list. – Henry Ecker Sep 21 '21 at 22:21
-
The top answer to the duplicate clearly explains the problem. It's not just that it's mutable, it's that list multiplication duplicates the references to the contents without copying them, so `[[0]] * 5` produces a `list` of five elements, all of which refer to the *same* `[0]` `list`. – ShadowRanger Sep 21 '21 at 22:22