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
๐ŸŒ
NumPy
numpy.org โ€บ devdocs โ€บ reference โ€บ generated โ€บ numpy.empty.html
numpy.empty โ€” NumPy v2.5.dev0 Manual
Unlike other array creation functions (e.g. zeros, ones, full), empty does not initialize the values of the array, and may therefore be marginally faster. However, the values stored in the newly allocated array are arbitrary. For reproducible behavior, be sure to set each element of the array ...
Top answer
1 of 16
611

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
149

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!

๐ŸŒ
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).

๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ stable โ€บ reference โ€บ generated โ€บ numpy.array.html
numpy.array โ€” NumPy v2.4 Manual
Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument. New in version 1.20.0. ... An array object satisfying the specified requirements. ... Return an empty array with shape and type of input.
๐ŸŒ
NumPy
numpy.org โ€บ devdocs โ€บ user โ€บ basics.creation.html
Array creation โ€” NumPy v2.5.dev0 Manual
You can use these methods to create ndarrays or Structured arrays. This document will cover general methods for ndarray creation. NumPy arrays can be defined using Python sequences such as lists and tuples. Lists and tuples are defined using [...] and (...), respectively.
Find elsewhere
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ what-is-the-numpyempty-function-in-python
What is the numpy.empty() function in Python?
This function returns an array of uninitialized data of the given shape, dtype and order. The objects of the array are initialized to none. ... Line 1: We import the numpy module.
๐ŸŒ
Spark Code Hub
sparkcodehub.com โ€บ numpy โ€บ basics โ€บ empty-array-initialization
Mastering NumPy empty(): High-Performance Array Initialization
np.empty() function is designed to create arrays quickly by allocating memory without initializing the elements, making it one of NumPyโ€™s fastest array creation methods.
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ python โ€บ third-party โ€บ numpy โ€บ empty
Python Numpy empty() - Create Empty Array | Vultr Docs
November 18, 2024 - The numpy.empty() function in Python is a part of the NumPy library, commonly used for generating arrays with uninitialized entries. This method proves useful primarily when you need to allocate an array quickly without immediately populating ...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ numpy โ€บ numpy_creating_arrays.asp
NumPy Creating Arrays
type(): This built-in Python function tells us the type of the object passed to it. Like in above code it shows that arr is numpy.ndarray type. To create an ndarray, we can pass a list, tuple or any array-like object into the array() method, and it will be converted into an ndarray:
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python โ€บ numpy
NumPy: Create an empty array (np.empty, np.empty_like)
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 ...
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 1.25 โ€บ reference โ€บ generated โ€บ numpy.empty.html
numpy.empty โ€” NumPy v1.25 Manual
Return a new array of given shape filled with value. ... empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster.
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ stable โ€บ user โ€บ absolute_beginners.html
NumPy: the absolute basics for beginners โ€” NumPy v2.4 Manual
Arrays should be constructed using `array`, `zeros` or `empty` (refer to the See Also section below). The parameters given here refer to a low-level method (`ndarray(...)`) for instantiating an array. For more information, refer to the `numpy` module and examine the methods and attributes of an array.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ what-is-the-preferred-method-to-check-for-an-empty-array-in-numpy
What is the preferred method to check for an empty array in NumPy?
March 26, 2026 - The most preferred and efficient method is using the size attribute, which returns the total number of elements in the array ? import numpy as np # Creating an empty array empty_array = np.array([]) # Creating a non-empty array data_array = ...
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 1.16 โ€บ reference โ€บ generated โ€บ numpy.empty.html
numpy.empty โ€” NumPy v1.16 Manual
February 18, 2020 - Return a new array of given shape and type, without initializing entries. ... Return an empty array with shape and type of input.
๐ŸŒ
Codegive
codegive.com โ€บ blog โ€บ numpy_make_an_empty_array.php
Numpy make an empty array
To create an empty NumPy array, use np.empty(shape, dtype=float, order='C'). This allocates memory for an array of the specified shape and data type without initializing its contents, making it extremely fast for pre-allocation when you plan to fill the array later.
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ numpy โ€บ methods โ€บ empty
NumPy empty()
numpy.empty(shape, dtype = float, order = 'C', like = None) The empty() method takes the following arguments: shape - desired new shape of the array (can be integer or tuple of integers) dtype (optional) - datatype of the returned array ยท order (optional) - specifies the order in which the uninitialized values are filled ยท