I need to create a matrix MxN where every element of the matrix is a list of integers. I need a list so that I can append new elements as I go, therefore a 3D matrix would not work here. I’m not sure if what I need here would actually be a list of lists.
Advertisement
Answer
The following function creates a 2D matrix of empty lists:
JavaScript
x
17
17
1
>>> def create(row,col):
2
return [[[] for _ in range(col)] for _ in range(row)]
3
4
>>> L = create(2,3)
5
>>> L[1][2].extend([1,2,3]) # add multiple integers at a location
6
>>> for row in L:
7
print(row)
8
9
[[], [], []]
10
[[], [], [1, 2, 3]]
11
>>> L[0][1].append(1) # add one more integer at a location
12
>>> for row in L:
13
print(row)
14
15
[[], [1], []]
16
[[], [], [1, 2, 3]]
17
How it works:
[]
is a new instance of an empty list.[[] for _ in range(col)]
uses a list comprehension to create a list of “col” empty lists.[[] for _ in range(col)] for _ in range(row)
create “row” new lists of “col” empty lists.