Jun Hyuk Kim's Blog
Making 2D arrays: Don't use [[0] * arr_len] * arr_len 본문
Coding Problems
Making 2D arrays: Don't use [[0] * arr_len] * arr_len
junhyuk1229 2022. 12. 19. 14:07Learned that when using python
[[0] * width] * height
Is wrong and
[[0 for _ in range(width)] for __ in range(height)]
Is correct to make 2d arrays

As you can see when the first_arr[1][2] is set to '1' all the other rows are affected too.
I think this is because when
first_arr = [[0] * width] * height
is inputed, first a row with 'width' number of '0' is made. Then the same list is made as an instance to the array.
While searching online I learned that
first_arr = [[0] * width for _ in range(height)]
Is the fastest way to make a 2D array.
'Coding Problems' 카테고리의 다른 글
| [Python] About round function in python (0) | 2023.09.22 |
|---|---|
| About using sys.stdin vs input in python3 (0) | 2023.01.04 |
| Fixing code in steps and combining (0) | 2022.12.21 |