Home > Enterprise >  Initializing 2D list in python with variable rows and columns
Initializing 2D list in python with variable rows and columns

Time:11-15

I have been trying to write a program in which we require to create a 2D list (array) in python with variable (not set while initialising) rows and columns. I know that in case of 1D list we can simply write:

a = []

in which the length is not set initially. But in the case of 2D list (array) the syntax:

a1 = [][]

is labelled incorrect (shows an error). When I looked it up in the Internet, I found out that the correct syntax is:

a1 = [[]* (some integer)]*[(some integer)]

This indeed worked, the only problem being that the dimensions of the matrix (2D array) was already set while initialising. Would someone please help me out?

CodePudding user response:

How I would initialize a matrix from lists in python:

w = 3
h = 3
a = []
for i in range(h):
    a.append([0]*w)

The syntax you found on the internet is incorrect as what I'm assuming it's trying to do is create a list of lists of lists, the innermost lists containing just one integer each. However trying to run it produces a syntax error as the brackets aren't even closed properly. Moreover, trying to initialize a matrix in one line would result in the exact same 1D list being copied multiple times in the 2D matrix, so attempting to modify one will modify every row.

Here are my methods for extending number of rows:

a.append([0]*len(a[0]))

number of columns:

for i in range(len(a)):
    a[i].append(0)

However I would strongly, strongly suggest numpy in large projects as there is nothing stopping you here from modifying the length of just one row, hence corrupting your entire matrix.

  • Related