Skip to content
Advertisement

How to create a matrix of lists?

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:

>>> def create(row,col):
...     return [[[] for _ in range(col)] for _ in range(row)]
...
>>> L = create(2,3)
>>> L[1][2].extend([1,2,3]) # add multiple integers at a location
>>> for row in L:
...   print(row)
...
[[], [], []]
[[], [], [1, 2, 3]]
>>> L[0][1].append(1) # add one more integer at a location
>>> for row in L:
...   print(row)
...
[[], [1], []]
[[], [], [1, 2, 3]]

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.
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement