0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much. I will try this. I am sorry that I forgot to put a bracket after the second *
Is shape a required atribute in ndarray command (numpy)?
yes, I'm not a numpy expert but as long as a function parameter is not defined with a = (example, dtype=float), it is required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.