🪴 notes

Search

Search IconIcon to open search

initializing a 2d array in python

Published May 9, 2023 Last updated May 9, 2023 Edit Source

I want to initialize an array like this: [[0,0],[0,0],...x]

1
arr = [[]] * num

This way seem like it works, but the sub-array is only referenced. If you try to append to a sub array:

1
2
3
4
arr = [[]] * 2
arr[0].push(1)

# -> [[1],[1]]

Every sub-array get’s appended to since they’re only references to one array.

1
arr = [[] for i in range(num)]

This is the proper way to do it. Every sub-array is a it’s own instance.