This shows a fairly high-performance (although slower than initializing to exact size) way to fill in an array of unknown size in numpy:

data = numpy.zeros( (1, 1) )
N = 0
while True:
    row = ...
    if not row: break
    # assume every row has shape (K,)
    K = row.shape[0]
    if (N >= data.shape[0]):
        # over-expand: any ratio around 1.5-2 should produce good behavior
        data.resize( (N*2, K) )
    if (K >= data.shape[1]):
        # no need to over-expand: presumably less common
        data.resize( (N, K+1) )
    # add row to data
    data[N, 0:K] = row

# slice to size of actual data
data = data[:N, :]

Adapting to your case:

if count > temp.shape[0]:
    temp.resize( (max( temp.shape[0]*2, count+1 ), temp.shape[1]) )
if i > temp.shape[1]:
    temp.resize( (temp.shape[0], max(temp.shape[1]*2, i+1)) )
# now safe to use temp[count, i]

You may also want to keep track of the actual data sizes (max count, max i) and trim the array later.

Answer from Alex I on Stack Overflow
Top answer
1 of 1
2

The structure you have now, with all the data in a single list (list and array mean different things in Python by the way), actually makes it easier to get a column. If your record is of size r_len = 6, and you want col = 3 (the fourth column), you can do

>>> Student.student_array[col::r_len]
[1, 4, 7]

To store a 2D list, though, you need to place each student's information into a separate list in your loop:

current_student = [len(Student.student_array), name, course_name, mark1, mark2, mark3]
Student.student_array.append(current_student)

Notice that you do not need to maintain a separate count this way: the length of the outer list speaks for itself.

To get the data from col = 3 in a 2D array like this, use a comprehension:

>>> [s[col] for s in Student.student_array]
[1, 4, 7]

Keeping related information in an unlabeled format like that is generally a poor idea though. You can either add labels by using a library like pandas, which will maintain proper tables for you, or you can encapsulate each student's info into a small class. You can write your own class, or use something like a namedtuple:

Record = collections.namedtuple('Record', ['id', 'name', 'course', 'mark1', 'mark2', 'mark3'])

...

Student.student_array.append(Record(len(Student.student_array), name, course_name, mark1, mark2, mark3))

You can now extract mark1 for each student instead of a numerical index, which is liable to change and cause a maintenance problem later:

>>> [s.mark1 for s in Student.student_array]
[1, 4, 7]
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 160559 › empty-2d-array
python - Empty 2D Array [SOLVED] | DaniWeb
December 3, 2008 - For heavy numeric work, prefer NumPy arrays for performance and vectorization; initialize once you know dimensions: arr = numpy.zeros((rows, cols)) (NumPy zeros). More on the aliasing gotcha: Python FAQ: multidimensional lists. defaultdict docs: collections.defaultdict. hoe to write a generic code for creating a empty 2D array and dynamically insert values in it.
🌐
Stack Overflow
stackoverflow.com › questions › 34350815 › create-array-2-dimension-in-python-without-knowing-size-of-array
Create array 2 dimension in Python without knowing size of array - Stack Overflow
How to create array 2D in python when I don't know size of array 2D: myList =[[1,2,3], [1,3], [1,2,8], .....] my code is : myList=[[]] for i in range(0,len(data)): ...
🌐
Sentry
sentry.io › sentry answers › python › define a two-dimensional array in python
Python Define a Two-Dimensional Array or Matrix | Sentry
September 23, 2026 - Create a 2D array in Python using numpy.zeros for matrix operations, or a nested list comprehension if you want to avoid the numpy dependency
🌐
Julia Programming Language
discourse.julialang.org › general usage
How to initialize array with one unknow dimension size - General Usage - Julia Programming Language
November 25, 2021 - I am not able to find any example how to initialize 2D array with one unknown dimension. Normally I use: A = zeros(dim1,dim2) for ii = 1:dim2 A[:,ii] = some_function_returning_vector_of_dim1() end But very ofte…
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-using-2d-arrays-lists-the-right-way
Using 2D arrays/lists in Python - GeeksforGeeks
The code below, compares two ways of initializing a 2D list in Python. Using list multiplication ([[0]*cols]*rows) creates multiple references to the same inner list, causing aliasing where changes affect all rows. Using a nested list comprehension creates a separate list for each row, avoiding aliasing and correctly forming a 2D array.
Published: December 20, 2025
Find elsewhere
🌐
Python
mail.python.org › pipermail › tutor › 2001-May › 005254.html
[Tutor] creating a matrix of unknown dimensions(dimensions depend on input)
April 30, 2001 - Whenever we're storing a "mapping", we're thinking of a Python dictionary: ### >>> mytable = {} ## Initially, an empty dictionary >>> mytable[0, 0] = 42 ## Filling in an entry >>> mytable[0, 0] ## Looking up an entry 42 ### (For those who are curious, we're depending on Python's implicit knowledge that by saying "0, 0", we actually mean the tuple "(0, 0)".) This is even nicer than a two-dimensional array, because there isn't any fixed size to the dictionary; you don't even need to preallocate the dimensions.
🌐
Snakify
snakify.org › two-dimensional lists (arrays)
Two-dimensional lists (arrays) - Learn Python 3 - Snakify
Suppose that two numbers are given: the number of rows of n and the number of columns m. You must create a list of size n×m, filled with, say, zeros.
🌐
w3resource
w3resource.com › python-exercises › numpy › python-numpy-exercise-37.php
Python NumPy: Create a 2-dimensional array of size 2 x 3 - w3resource
August 29, 2025 - Write a NumPy program to create a 2-dimensional array of size 2 x 3 (composed of 4-byte integer elements), also print the shape, type and data type of the array. ... # Importing the NumPy library with an alias 'np' import numpy as np # Creating a 2D NumPy array with two rows and three columns with data type np.int32 x = np.array([[2, 4, 6], [6, 8, 10]], np.int32) # Checking and displaying the type of variable 'x' print(type(x)) # Displaying the shape of the NumPy array 'x' (number of rows, number of columns) print(x.shape) # Displaying the data type of the elements in the array 'x' print(x.dtype)
🌐
w3resource
w3resource.com › python-exercises › extended-data-types › python-extended-data-types-index-ellipsis-exercise-6.php
Creating multidimensional arrays with unspecified dimensions in Python
August 11, 2025 - Learn how to use 'Ellipsis' in a Python program to create multidimensional arrays with unspecified dimensions using NumPy. Explore code examples for handling arrays with placeholders.
🌐
GeeksforGeeks
geeksforgeeks.org › python-initialize-empty-array-of-given-length
Python - Initialize empty array of given length - GeeksforGeeks
Below, are the methods to Initialize an empty array of a given length in Python. ... In this example, we are using Python List comprehension for 1D and 2D empty arrays. Using list comprehension like [[0] * 4 for i in range(3)] creates independent lists for each row.
Published: November 26, 2024
🌐
Drbeane
drbeane.github.io › python_dsci › pages › array_2d.html
2-Dimensional Arrays — Python for Data Science
In this lesson, we will work exclusively with 2D arrays, which consist of several values arranged into ordered rows and columns. You can create a two dimensional array by applying np.array() to a list of lists, as long as the sublists are of the same size, and contain elements of a single data type.
🌐
MLJAR
mljar.com › answers › define-two-dimensional-array-python
Define two-dimensional array in Python
w = 6 # width, number of columns h = 4 # height, number of rows array = [[0 for x in range(w)] for y in range(h)] ... REMEMBER Be careful with idexing, you can't go out of range! ... This way is much easier. You can use zeros function from numpy to create 2D array with all values set to zero:
Top answer
1 of 7
1263

You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this "list comprehension".

# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5
Matrix = [[0 for x in range(w)] for y in range(h)] 

#You can now add items to the list:

Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range... 
Matrix[0][6] = 3 # valid

Note that the matrix is "y" address major, in other words, the "y index" comes before the "x index".

print Matrix[0][0] # prints 1
x, y = 0, 6 
print Matrix[x][y] # prints 3; be careful with indexing! 

Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix.

2 of 7
487

If you really want a matrix, you might be better off using numpy. Matrix operations in numpy most often use an array type with two dimensions. There are many ways to create a new array; one of the most useful is the zeros function, which takes a shape parameter and returns an array of the given shape, with the values initialized to zero:

>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

Here are some other ways to create 2-d arrays and matrices (with output removed for compactness):

numpy.arange(25).reshape((5, 5))         # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5))   # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5))    # pass a Python list and reshape
numpy.empty((5, 5))                      # allocate, but don't initialize
numpy.ones((5, 5))                       # initialize with ones

numpy provides a matrix type as well, but it is no longer recommended for any use, and may be removed from numpy in the future.

🌐
IncludeHelp
includehelp.com › python › initialise-numpy-array-of-unknown-length.aspx
Python - Initialise numpy array of unknown length
To initialise numpy array of unknown length, we can build a Python list and convert that to a Numpy array. That takes amortized O(1) time per append + O(n) for the conversion to the array, for a total of O(n). ... # Import numpy import numpy as np # Creating a list l = [] # Appending elements ...
🌐
W3Schools
w3schools.com › python › numpy › numpy_array_reshape.asp
NumPy Array Reshaping
Try converting 1D array with 8 elements to a 2D array with 3 elements in each dimension (will raise an error): import numpy as np arr = np.array([1, 2, 3, 4, 5, 6, 7, 8]) newarr = arr.reshape(3, 3) print(newarr) Try it Yourself » ... import numpy as np arr = np.array([1, 2, 3, 4, 5, 6, 7, 8]) print(arr.reshape(2, 4).base) Try it Yourself » · The example above returns the original array, so it is a view. You are allowed to have one "unknown" dimension.