Stack Exchange
Stack Overflow
Questions
Tags
Users
About
Stack Overflow
Public
Questions
Tags
Users
About
Appending to arr[0] where a = [[]]*n. Python
Asked
Dec 09 '21 at 00:42
Active
Dec 09 '21 at 00:42
Viewed
15 times
0
Why code:
hl = [[]]*3 hl[0].append(1) return hl
gives [[1],[1],[1]] instead of [[1],[],[]]?
python
asked Dec 09 '21 at 00:42
Mateusz Matyjaszczyk
1
3
1
because `hl = [[]]*3` creates a list with three references *to the same empty list*. The same as if you did `empty = []; hl = [empty, empty, empty]`
–
juanpa.arrivillaga
Dec 09 '21 at 00:44
1
A solution: `hl = [[] for _ in range(3)]`
–
juanpa.arrivillaga
Dec 09 '21 at 00:45
0 Answers
0