There is no need to use a loop. You can use numpy.arange([start, ]stop, [step, ]) to generate a range of numbers.

In your case:

predicted_value = np.arange(9, 33)  # Note the 33 if you want 9..32

If you really want to use a loop, there is the option of using a list comprehension:

predicted_value = np.array([i for i in range(9, 33)])

Or an explicit loop, which would be most horrible:

predicted_value = np.empty(33 - 9)
for k, i in enumerate(range(9, 33)):
    predicted_value[k] = i
Answer from MB-F on Stack Overflow
🌐
W3Schools
w3schools.com › python › numpy › numpy_array_iterating.asp
NumPy Array Iterating
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 ...
Discussions

python - how to use for loop with numpy array? - Stack Overflow
Currently it is somewhat misleading ... about for loops. It is about initializing an array with a sequence of numbers, if I am not mistaken. ... You could also skip the first code snippet since it is irrelevant to your actual question. Ivan A. – Ivan A. 2017-03-06 18:15:13 +00:00 Commented Mar 6, 2017 at 18:15 ... Save this answer. ... Show activity on this post. There is no need to use a loop. You can use numpy.arange([start, ... More on stackoverflow.com
🌐 stackoverflow.com
Looping through each item in a numpy array? - Stack Overflow
You can iterate through it in the same way by iterating through it in the same way. Try it and see! However, iterating through a 2D array completely defeats the point of using numpy, i.e. efficient array operations. Read this doc page, for instance. More on stackoverflow.com
🌐 stackoverflow.com
python - best way to create numpy array from FOR loop - Stack Overflow
Is there a better way to create a multidimensional array in numpy using a FOR loop, rather than creating a list? This is the only method I could come up with: import numpy as np a = [] for x in ... More on stackoverflow.com
🌐 stackoverflow.com
python - Iterating over a numpy array - Stack Overflow
Is there a less verbose alternative to this: for x in xrange(array.shape[0]): for y in xrange(array.shape[1]): do_stuff(x, y) I came up with this: for x, y in itertools.product(map(xr More on stackoverflow.com
🌐 stackoverflow.com
🌐
Pluralsight
pluralsight.com › blog › tech guides & tutorials
Iterating Numpy Arrays | Pluralsight
November 12, 2018 - To iterate each cell in the two-dimensional array, nest the for loop.
🌐
NumPy
numpy.org › doc › stable › reference › arrays.nditer.html
Iterating over arrays — NumPy v2.5 Manual
By default, the nditer uses the flags ‘allocate’ and ‘writeonly’ for operands that are passed in as None. This means we were able to provide just the two operands to the iterator, and it handled the rest. When adding the ‘out’ parameter, we have to explicitly provide those flags, because if someone passes in an array as ‘out’, the iterator will default to ‘readonly’, and our inner loop would fail.
🌐
GeeksforGeeks
geeksforgeeks.org › python › numpy-iterating-over-array
Numpy - Iterating Over Arrays - GeeksforGeeks
July 23, 2025 - import numpy as np # Create a 2D ... three rows and three columns. for row in arr_2d: loops through each row of the 2D array, treating it as a separate one-dimensional array....
🌐
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 - The basic syntax of the numpy for loop operation is a for with a colon and followed by the python indentation, and we can perform the operation inside this block which allows us to iterate through each element in the given array, and we can ...
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
Find elsewhere
🌐
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]}")
🌐
Stack Overflow
stackoverflow.com › questions › 6967463 › iterating-over-a-numpy-array
python - Iterating over a numpy array - Stack Overflow
Is there a less verbose alternative to this: for x in xrange(array.shape[0]): for y in xrange(array.shape[1]): do_stuff(x, y) I came up with this: for x, y in itertools.product(map(xr...
🌐
NumPy
numpy.org › doc › 2.1 › reference › arrays.nditer.html
Iterating over arrays — NumPy v2.1 Manual
By default, the nditer uses the flags ‘allocate’ and ‘writeonly’ for operands that are passed in as None. This means we were able to provide just the two operands to the iterator, and it handled the rest. When adding the ‘out’ parameter, we have to explicitly provide those flags, because if someone passes in an array as ‘out’, the iterator will default to ‘readonly’, and our inner loop would fail.
🌐
Tudelft
nsweb.tn.tudelft.nl › ~gsteele › TN2513_Tips › Creating a numpy array in a loop.html
Creating a numpy array in a loop
y is: <class 'numpy.ndarray'> [ 0. 1. 4. 9. 16. 25. 36. 49. 64. 81.] This is the most computationally efficient way, but it only works if you know in advance how big the final array will be! If you don't know how big it will be in then end, the first example with lists is probably your best bet. ... N = 10 # Pre-allocate an array of the right size y = np.zeros(N) # Now fill the arry for i in range(N): x = i y[i] = x**2 print("y is:") print(type(y)) print(y)
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to loop through numpy arrays in python
5 Best Ways to Loop Through NumPy Arrays in Python - Be on the Right Side of Change
February 20, 2024 - It works very similarly to iterating over a regular Python list, but it might not be the most efficient way when working with large arrays due to its Python-level loop overhead. ... This code snippet creates a NumPy array with elements from 1 to 5. It then iterates over the array using a basic for-loop, printing each element to the console.
Top answer
1 of 2
9

You should use the builtin function nditer, if you don't need to have the indexes values.

for elem in np.nditer(arr01):
    print(elem)

EDIT: If you need indexes (as a tuple for 2D table), then:

for index, elem in np.ndenumerate(arr01):
    print(index, elem)
2 of 2
2

Seems like you've skipped over some intro Python chapters. With a list there are several simple ways of iterating:

In [1]: alist = ['a','b','c']                                                   
In [2]: for i in alist: print(i)        # on the list itself                                                
a
b
c
In [3]: len(alist)                                                              
Out[3]: 3
In [4]: for i in range(len(alist)): print(i,alist[i])  # index is ok                 
0 a
1 b
2 c
In [5]: for i,v in enumerate(alist): print(i,v)   # but enumerate is simpler            
0 a
1 b
2 c

Note the indexes. range(3) is sufficient. alist[3] produces an error.

In [6]: arr = np.arange(6).reshape(2,3)                                         
In [7]: arr                                                                     
Out[7]: 
array([[0, 1, 2],
       [3, 4, 5]])
In [8]: for row in arr: 
   ...:     for col in row: 
   ...:         print(row,col) 
   ...:                                                                         
[0 1 2] 0
[0 1 2] 1
[0 1 2] 2
[3 4 5] 3
[3 4 5] 4
[3 4 5] 5

The shape is a tuple. The row count is then arr.shape[0], and columns arr.shape[1]. Or you can 'unpack' both at once:

In [9]: arr.shape                                                               
Out[9]: (2, 3)
In [10]: n,m = arr.shape                                                        
In [11]: [arr[i,j] for i in range(n) for j in range(m)]                         
Out[11]: [0, 1, 2, 3, 4, 5]

But we can get the same flat list of values with ravel and optional conversion to list:

In [12]: arr.ravel()                                                            
Out[12]: array([0, 1, 2, 3, 4, 5])
In [13]: arr.ravel().tolist()                                                   
Out[13]: [0, 1, 2, 3, 4, 5]

But usually with numpy arrays, you shouldn't be iterating at all. Learn enough of the numpy basics so you can work with the whole array, not elements.

nditer can be used, as the other answer shows, to iterate through an array in a flat manner, but there are a number of details about it that could easily confuse a beginner. There are a couple of intro pages to nditer, but they should be read in full. Usually I discourage its use.

In [14]: for i in np.nditer(arr): 
    ...:     print(i, type(i), i.shape) 
    ...:                                                                        
0 <class 'numpy.ndarray'> ()        # this element is a 0d array, not a scalar integer
1 <class 'numpy.ndarray'> ()
2 <class 'numpy.ndarray'> ()
... 

Iterating with ndenumerate or on the tolist produce different types of elements. The type may matter if you try to do more than display the value, so be careful.

In [15]: list(np.ndenumerate(arr))                                              
Out[15]: [((0, 0), 0), ((0, 1), 1), ((0, 2), 2), ((1, 0), 3), ((1, 1), 4), ((1, 2), 5)]
In [16]: for ij, v in np.ndenumerate(arr): 
    ...:     print(ij, v, type(v)) 
    ...:                                                                        
(0, 0) 0 <class 'numpy.int64'>
(0, 1) 1 <class 'numpy.int64'>
...
In [17]: for i, v in enumerate(arr.ravel().tolist()): 
    ...:     print(i, v, type(v)) 
    ...:                                                                        
0 0 <class 'int'>
1 1 <class 'int'>
...
🌐
Finxter
blog.finxter.com › home › learn python blog › how to iterate over a numpy array
How to Iterate over a NumPy Array - Be on the Right Side of Change
August 16, 2022 - Next, a while loop is instantiated and iterates through the elements of atomic_names. This will continue while the value of el_count remains less than the value of atomic_names.size. The output is sent to the terminal on one (1) line as an additional argument is passed to the print statement (end=' '). This argument replaces the default newline character with a blank space. This method uses a For loop and np.ndenumerate() to iterate through a NumPy array.
🌐
NumPy
numpy.org › doc › 2.3 › reference › arrays.nditer.html
Iterating over arrays — NumPy v2.3 Manual
By default, the nditer uses the flags ‘allocate’ and ‘writeonly’ for operands that are passed in as None. This means we were able to provide just the two operands to the iterator, and it handled the rest. When adding the ‘out’ parameter, we have to explicitly provide those flags, because if someone passes in an array as ‘out’, the iterator will default to ‘readonly’, and our inner loop would fail.
🌐
Reddit
reddit.com › r/learnpython › why can't i easily loop over numpy arrays
r/learnpython on Reddit: Why can't I easily loop over numpy arrays
December 12, 2018 -

I get they are vectorized but it seems needlessly difficult to only allow vector math and not let me do a normal for loop over my ndarrays.

I have a binary array laced with zeros eg. (-1, 1, 1, 0, 0, 0, 1, 1) I want to loop through the array and find indexes, in order.

So in my ex the return would be: [0:-1, 1:1, 2:1, 3:0... etc]

I got the vars I need w:

x = np.where(array>= 1)
y = np.where(array<= -1)

however theyre stored seperately in 2 vars and are out of order. Ideas anyone?

🌐
Hyperskill
hyperskill.org › university › numpy › numpy-array-iterating
NumPy Array Iterating
September 4, 2024 - NumPy arrays provide several iterating methods to efficiently manipulate and process data. One common way to iterate through elements in a NumPy array is by using a for loop. When iterating over a one-dimensional array, the loop traverses each element individually.