You could preallocate the array before assigning the respective values:

a = np.empty(shape=(25, 2), dtype=int)
for x in range(1, 6):
    for y in range(1, 6):
        index = (x-1)*5+(y-1)
        a[index] = x, y
Answer from aasoo on Stack Overflow
🌐
Tudelft
nsweb.tn.tudelft.nl › ~gsteele › TN2513_Tips › Creating a numpy array in a loop.html
Creating a numpy array in a loop
As is always the case in coding, there are a couple of different ways to do this, we show some of them here. One way to do this is to use a list to collect your values and then convert it at the end to a numpy array. If you like lists, this is quick and handy.
Discussions

python - Construct an numpy array inside a for loop - Stack Overflow
I am trying to load a database from my python code which contains a list of dictionaries. For each item of the list the dictionary contains the name of a file a sub-list which contains n different More on stackoverflow.com
🌐 stackoverflow.com
python - Most efficient and most pythonic way to create a NumPy array within a loop - Stack Overflow
New: Stack Overflow For Agents. The next generation of knowledge exchange. Learn more · Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I'm currently trying to figure out the most efficient way to create a numpy array in a loop... More on stackoverflow.com
🌐 stackoverflow.com
July 10, 2017
python - how create numpy array with for loop - Stack Overflow
Hello sorry for my english i'm not native and not good so i have some question I am creating a function in python that multiplies a desired number by a whole consecutive integer. the heart of my pr... More on stackoverflow.com
🌐 stackoverflow.com
Building up an array in numpy/scipy by iteration in Python? - Stack Overflow
That makes sense, but suppose I ... allocate numpy.zeros(1, 1000) but only use 50 elements, I don't want to iterate until I hit a zero... the approach of overallocating seems to create this weird situation where each array data type will require a different "stop" condition for looping... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Akuederle
akuederle.com › quicktips › create-numpy-array-with-for-loop
The proper way to create a numpy array inside a for-loop
April 14, 2015 - If you came across the same issue, I described above, consider using a simple python list, and converting it to a numpy array at the end (this is way faster!). If you know the exact size of the final array (which I assumed you do not), you can also try initializing an empty array with this size first and then replace certain parts by index inside of the loop.
🌐
EDUCBA
educba.com › home › software development › software development tutorials › numpy tutorial › numpy for loop
NumPy for loop | Learn the Examples of NumPy for loop
April 3, 2023 - In this example, we have created an array and iterated it twice using python for a loop. This method allows us to perform different operations while iterating multiple times, and this method is very efficient and requires less coding. In this example, we have created a zero-dimensional array and converted it into a two-dimensional array. ... import numpy as np arr = np.array([[[8, 16, 44], [0, 4, 7]], [[22, 40, 16], [7, 14, 21]]]) for x in arr: for y in x: for z in y: print(z)
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
TutorialsPoint
tutorialspoint.com › numpy › numpy_iterating_over_array.htm
NumPy - Iterating Over Array
This approach allows for more precise control over element access and manipulation compared to simple element iteration. ... In the following example, we iterate over each element of the 2D array using nested loops. We access and print each element's value along with its indices − · import numpy as np # Create a 2-dimensional NumPy array arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Get the dimensions of the array rows, cols = arr_2d.shape # Iterate over the array using indices for i in range(rows): for j in range(cols): print(f"Element at ({i}, {j}): {arr_2d[i, j]}")
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 62599397 › how-create-numpy-array-with-for-loop
python - how create numpy array with for loop - Stack Overflow
Incidentally, in R you’d do something equivalent (along the lines of seq(n) * x): R uses loops even less than Python; and what you suggested would be inefficient and unnecessarily convoluted in R.
Top answer
1 of 4
36

NumPy provides a 'fromiter' method:

def myfunc(n):
    for i in range(n):
        yield i**2


np.fromiter(myfunc(5), dtype=int)

which yields

array([ 0,  1,  4,  9, 16])
2 of 4
19

The recommended way to do this is to preallocate before the loop and use slicing and indexing to insert

my_array = numpy.zeros(1,1000)
for i in xrange(1000):
    #for 1D array
    my_array[i] = functionToGetValue(i)
    #OR to fill an entire row
    my_array[i:] = functionToGetValue(i)
    #or to fill an entire column
    my_array[:,i] = functionToGetValue(i)

numpy does provide an array.resize() method, but this will be far slower due to the cost of reallocating memory inside a loop. If you must have flexibility, then I'm afraid the only way is to create an array from a list.

EDIT: If you are worried that you're allocating too much memory for your data, I'd use the method above to over-allocate and then when the loop is done, lop off the unused bits of the array using array.resize(). This will be far, far faster than constantly reallocating the array inside the loop.

EDIT: In response to @user248237's comment, assuming you know any one dimension of the array (for simplicity's sake):

my_array = numpy.array(10000, SOMECONSTANT)

for i in xrange(someVariable):
    if i >= my_array.shape[0]:
        my_array.resize((my_array.shape[0]*2, SOMECONSTANT))

    my_array[i:] = someFunction()

#lop off extra bits with resize() here

The general principle is "allocate more than you think you'll need, and if things change, resize the array as few times as possible". Doubling the size could be thought of as excessive, but in fact this is the method used by several data structures in several standard libraries in other languages (java.util.Vector does this by default for example. I think several implementations of std::vector in C++ do this as well).

🌐
W3Schools
w3schools.com › python › numpy › numpy_array_iterating.asp
NumPy Array Iterating
import numpy as np arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) for x in arr: for y in x: for z in y: print(z) Try it Yourself » · The function nditer() is a helping function that can be used from very basic to very advanced iterations. It solves some basic issues which we face in iteration, lets go through it with examples. In basic for loops, iterating through each scalar of an array we need to use n for loops which can be difficult to write for arrays with very high dimensionality.
🌐
NumPy
numpy.org › doc › stable › reference › arrays.nditer.html
Iterating over arrays — NumPy v2.5 Manual
One thing to watch out for is conversions back to the original data type when using a read-write or write-only operand. A common case is to implement the inner loop in terms of 64-bit floats, and use ‘same_kind’ casting to allow the other floating-point types to be processed as well. While in read-only mode, an integer array could be provided, read-write mode will raise an exception because conversion back to the array would violate the casting rule.
🌐
Numba Discussion
numba.discourse.group › support: how do i do ...? › creating numpy arrays from arrays
Creating numpy arrays from arrays - Support: How do I do ...? - Numba Discussion
January 29, 2023 - Hi, in reference to issue: #4470 , are there any workarounds to create numpy arrays from arrays. My sample code #4470 is: import numpy as np import numba @numba.njit def myfunc(mol1Coord,mol2Coord): for j in numba.prange(int(mol2Coord.shape[0]/3)): rIVec=np.array([mol1Coord[0],mol1Coord[0]...
🌐
SciPy Lecture Notes
scipy-lectures.org › intro › numpy › array_object.html
1.4.1. The NumPy array object — Scipy lecture notes
Slicing: Arrays, like other Python sequences can also be sliced: ... Try the different flavours of slicing, using start, end and step: starting from a linspace, try to obtain odd numbers counting backwards, and even numbers counting forwards. Reproduce the slices in the diagram above. You may use the following expression to create the array:
🌐
GeeksforGeeks
geeksforgeeks.org › python › numpy-iterating-over-array
Numpy - Iterating Over Arrays - GeeksforGeeks
July 23, 2025 - import numpy as np # Create a 2D array arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Iterate over rows for row in arr_2d: print(row) ... arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) creates a 2D array with three rows and three ...