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:

JavaScript

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