That is the wrong mental model for using NumPy efficiently. NumPy arrays are stored in contiguous blocks of memory. To append rows or columns to an existing array, the entire array needs to be copied to a new block of memory, creating gaps for the new elements to be stored. This is very inefficient if done repeatedly.

Instead of appending rows, allocate a suitably sized array, and then assign to it row-by-row:

>>> import numpy as np

>>> a = np.zeros(shape=(3, 2))
>>> a
array([[ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.]])

>>> a[0] = [1, 2]
>>> a[1] = [3, 4]
>>> a[2] = [5, 6]

>>> a
array([[ 1.,  2.],
       [ 3.,  4.],
       [ 5.,  6.]])
Answer from Stephen Simmons on Stack Overflow
Top answer
1 of 16
612

That is the wrong mental model for using NumPy efficiently. NumPy arrays are stored in contiguous blocks of memory. To append rows or columns to an existing array, the entire array needs to be copied to a new block of memory, creating gaps for the new elements to be stored. This is very inefficient if done repeatedly.

Instead of appending rows, allocate a suitably sized array, and then assign to it row-by-row:

>>> import numpy as np

>>> a = np.zeros(shape=(3, 2))
>>> a
array([[ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.]])

>>> a[0] = [1, 2]
>>> a[1] = [3, 4]
>>> a[2] = [5, 6]

>>> a
array([[ 1.,  2.],
       [ 3.,  4.],
       [ 5.,  6.]])
2 of 16
150

A NumPy array is a very different data structure from a list and is designed to be used in different ways. Your use of hstack is potentially very inefficient... every time you call it, all the data in the existing array is copied into a new one. (The append function will have the same issue.) If you want to build up your matrix one column at a time, you might be best off to keep it in a list until it is finished, and only then convert it into an array.

e.g.


mylist = []
for item in data:
    mylist.append(item)
mat = numpy.array(mylist)

item can be a list, an array or any iterable, as long as each item has the same number of elements.
In this particular case (data is some iterable holding the matrix columns) you can simply use


mat = numpy.array(data)

(Also note that using list as a variable name is probably not good practice since it masks the built-in type by that name, which can lead to bugs.)

EDIT:

If for some reason you really do want to create an empty array, you can just use numpy.array([]), but this is rarely useful!

🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.empty.html
numpy.empty — NumPy v2.5 Manual
Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None. ... Return an empty array with shape and type of input.
Discussions

python - How to make a 2d numpy array from an empty numpy array by adding 1d numpy arrays? - Stack Overflow
this is what i get when i try this on an empty numpy array, ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 0 and the array at index 1 has size 8 2022-09-22T16:52:31.19Z+00:00 More on stackoverflow.com
🌐 stackoverflow.com
Python/numpy issue with array/vector with empty second dimension - Stack Overflow
It takes steps to ensure that most ... another 2d matrix: In [247]: ym=np.matrix(y) In [248]: ym.sum(axis=1) Out[248]: matrix([[ 6], [22], [38]]) ... The _collapse bit lets it return a scalar for ym.sum(). ... Sign up to request clarification or add additional context in comments. ... Is there a way to have keepdims=True be the default? It's an awful lot to type again and again. 2015-04-17T02:42:02.917Z+00:00 ... For me it seems that taking the transpose of a (2L,) array should make numpy realize you ... More on stackoverflow.com
🌐 stackoverflow.com
How can I create a truly empty numpy array which can be merged onto (by a recursive function)?
I can't say I fully followed your problem statement, but you can create an array with a total size of zero if any of the dimensions has size zero: a = np.empty((0, 3)) # Doesn't really matter if you use `empty`, `zeros` or `ones` here Zero-size arrays are the neutral element wrt. concatenation along their zero-size dimension (if that's what you mean by "merging"): b = np.random.uniform(size=(20, 3)) c = np.concatenate([a, b], 0) (c == b).all() # True More on reddit.com
🌐 r/learnpython
2
2
September 21, 2023
python - NUMPY: What does np.empty(()) do in 2D arrays? - Stack Overflow
Don't use np.empty unless you intend to set every element in some way or other. That's the implication of the arbitrary. ... Save this answer. ... Show activity on this post. Array of uninitialized (arbitrary) data of the given shape, dtype, and order More on stackoverflow.com
🌐 stackoverflow.com
🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.empty.html
numpy.empty — NumPy v2.2 Manual
Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None. ... Return an empty array with shape and type of input.
🌐
w3resource
w3resource.com › numpy › array-creation › empty.php
NumPy: numpy.empty() function - w3resource
In the second example, an empty 2D array of size (2, 2) is created with the specified data type float. The resulting array contains four undefined floating-point values. The values shown in the output are also machine-dependent and may vary ...
🌐
Numpyarray
numpyarray.com › numpy-empty-2d-array.html
NumPy empty 2D array – Numpy Array
NumPy empty 2D array is a fundamental concept in NumPy, the popular numerical computing library for Python. Unlike other array creation functions like zeros() or ones(), the empty() function creates an array without initializing its elements.
🌐
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.
🌐
Appdividend
appdividend.com › create-and-check-if-a-numpy-array-is-empty
How to Create and Check If a Numpy Array is Empty
July 10, 2025 - ... import numpy as np arr3d = np.empty((2, 0, 4)) # 2 rows 0 columns 4 depth print(arr3d) print(arr3d.size) print(arr3d.shape) # Output: # [] # 0 # (2, 0, 4) The most Pythonic way to check if an array is empty is to use the .size attribute.
Find elsewhere
🌐
Sentry
sentry.io › sentry answers › python › define a two-dimensional array in python
Define a two-dimensional array in Python | Sentry
June 15, 2023 - import numpy matrix = ... this operation. To create a 2D array without using numpy, we can initialize a list of lists using a list comprehension....
Top answer
1 of 2
7

While you can reshape arrays, and add dimensions with [:,np.newaxis], you should be familiar with the most basic nested brackets, or list, notation. Note how it matches the display.

In [230]: np.array([[0],[6]])
Out[230]: 
array([[0],
       [6]])
In [231]: _.shape
Out[231]: (2, 1)

np.array also takes a ndmin parameter, though it add extra dimensions at the start (the default location for numpy.)

In [232]: np.array([0,6],ndmin=2)
Out[232]: array([[0, 6]])
In [233]: _.shape
Out[233]: (1, 2)

A classic way of making something 2d - reshape:

In [234]: y=np.arange(12).reshape(3,4)
In [235]: y
Out[235]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

sum (and related functions) has a keepdims parameter. Read the docs.

In [236]: y.sum(axis=1,keepdims=True)
Out[236]: 
array([[ 6],
       [22],
       [38]])
In [237]: _.shape
Out[237]: (3, 1)

empty 2nd dimension isn't quite the terminology. More like a nonexistent 2nd dimension.

A dimension can have 0 terms:

In [238]: np.ones((2,0))
Out[238]: array([], shape=(2, 0), dtype=float64)

If you are more familiar with MATLAB, which has a minimum of 2d, you might like the np.matrix subclass. It takes steps to ensure that most operations return another 2d matrix:

In [247]: ym=np.matrix(y)
In [248]: ym.sum(axis=1)
Out[248]: 
matrix([[ 6],
        [22],
        [38]])

The matrix sum does:

np.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis)

The _collapse bit lets it return a scalar for ym.sum().

2 of 2
3

There is another point to keep dimension info:

In [42]: X
Out[42]: 
array([[0, 0],
       [0, 1],
       [1, 0],
       [1, 1]])

In [43]: X[1].shape
Out[43]: (2,)

In [44]: X[1:2].shape
Out[44]: (1, 2)

In [45]: X[1]
Out[45]: array([0, 1])

In [46]: X[1:2]  # this way will keep dimension
Out[46]: array([[0, 1]])
🌐
Python Guides
pythonguides.com › create-an-empty-array-in-python
Ways to Initialize an Empty Python Array
January 12, 2026 - For instance, if I am tracking the monthly temperatures for 5 major US cities over 12 months, I create an empty 2D Python array. import numpy as np # Creating an empty 2D Python array (5 cities x 12 months) # We use np.empty which is faster than np.zeros because it doesn't initialize values city_temps = np.empty((5, 12)) print(f"Shape of Python Array: {city_temps.shape}") print("The array contains uninitialized data (random memory values).")
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › numpy empty array with examples
NumPy Empty Array With Examples - Spark By {Examples}
March 27, 2024 - NumPy empty() array function in Python is used to create a new array of given shapes and types, without initializing entries. This function takes three
🌐
Python Guides
pythonguides.com › python-numpy-empty-array
Create An Empty Array Using NumPy In Python
May 16, 2025 - NumPy’s empty() function in Python is the fastest way to create an empty array as it allocates memory without initializing the values. import numpy as np # Create a 1D empty array of size 5 empty_array_1d = np.empty(5) print("1D Empty Array:") print(empty_array_1d) # Create a 2D empty array ...
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.empty.html
numpy.empty — NumPy v2.6.dev0 Manual
Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None. ... Return an empty array with shape and type of input.
🌐
Reddit
reddit.com › r/learnpython › how can i create a truly empty numpy array which can be merged onto (by a recursive function)?
r/learnpython on Reddit: How can I create a truly empty numpy array which can be merged onto (by a recursive function)?
September 21, 2023 -

I'm kind of stuck conceptually on how to make this happen. I have a recursive method that builds a binary tree, and stores the tree as an instance variable. However, the function is not allowed to return anything, so each recursive call should (according to me) modify in-place the tree instance variable. However, I'm not sure how to set up my instance variable such that all said and done it holds a multidimensional array that represents the tree.

Say I set initialize it as a 1x1 array with element zero as a placeholder. Then as I go about recursing through my tree I can merge to it... but at the end I'm left with a spare [0] element that I don't need. In this case, I'd need some kind of final stop condition and function to remove that unnecessary placeholder stump. I don't think this is possible?

Otherwise, say I initialize the instance variable as None. Then when the first series of recursive calls, it would have to reassign the tree variable to change from None to an ndarray object, but all future calls would have to merge to the array. I don't think this is what the function should be asked to do?

Is there a way to make a truly empty array that I can merge onto? (e.g. np.empty doesn't reallly give an empty array, it gives an array with placeholder values so I'm still left with a useless stump at the end).

🌐
Note.nkmk.me
note.nkmk.me › home › python › numpy
NumPy: Create an empty array (np.empty, np.empty_like) | note.nkmk.me
January 22, 2024 - This article explains how to create an empty array (ndarray) in NumPy. There are two methods available: np.empty(), which allows specifying any shape and data type (dtype), and np.empty_like(), which ...
🌐
Sharp Sight
sharpsight.ai › blog › numpy-empty
How to Use Numpy Empty - Sharp Sight
February 6, 2024 - Remember in the review of NumPy earlier in this tutorial, I explained that NumPy arrays have a shape. The shape is essentially the number of rows and the number of columns (if you have a 2D array). When you create an array with np.empty, you need to specify the exact shape of the output by using the shape parameter.
🌐
Stack Overflow
stackoverflow.com › questions › 59913289 › numpy-what-does-np-empty-do-in-2d-arrays
python - NUMPY: What does np.empty(()) do in 2D arrays? - Stack Overflow
What does np.empty(()) actually do? For instance, if I want to make an empty array of 5 rows and 5 cols, I would use np.empty((5,5)). This gives a random output like: [[0.57061489 0.57883359 0.57...
🌐
Finxter
blog.finxter.com › home › learn python blog › how to create a two dimensional array in python?
How To Create a Two Dimensional Array in Python? - Be on the Right Side of Change
June 11, 2022 - Here’s a diagrammatic representation ... If you want to create an empty 2D array without using any external libraries, you can use nested lists....