How to define an empty 2 dimensional list instead of data = [["",""],["",""],["",""],["",""]]

Viewed 56

How to define an empty 2 dimensional list instead of data = [["",""],["",""],["",""],["",""]] For larger number of elements

5 Answers

This is a possible solution:

data = [['' for j in range(m)] for i in range(n)]

m and n are the desired dimensions of your list of lists.

lis = [[] for _ in range(3)] try it

A simple list comprehension will do:

data = [["", ""] for i in range(4)]
   #initialize an empty 2d list
data = [[]]

#append to first list
data[0].append("a")
data[0].append("b")
data[0].append("c")

#append another list to the 2D list
data.append(['d','e','f'])

print(data)

this way you can make your rows or columns of any length

My approach to this problem would use NumPy, a math and data manipulation library for python. In that library, there's a very simple way of accomplishing this. If I want to generate an empty matrix built to hold m rows of n strings, I'd do it like this:

import numpy as np    # import the library

m = 32
n = 16    # choose your array dimensions

data = np.empty((m, n), dtype=str)    # create the empty data array

In order to use NumPy, you'll need to install it with the terminal command, pip install numpy.

Related