# Append to numpy array in loop

To append elements to a NumPy array within a loop, you can use the `numpy.append()` function. Here’s the syntax:

``````import numpy as np

# Create an empty array or an array with initial values
my_array = np.array([])  # or np.array([1, 2, 3])

# Loop to append elements
for i in range(n):
# Generate a new element
new_element = ...

# Append the new element to the array
my_array = np.append(my_array, new_element)
``````

## Append to numpy array in the loop example

Here’s an example that demonstrates how to append elements to a NumPy array within a loop:

``````import numpy as np

# Create an empty array
my_array = np.array([])

# Loop to append elements
for i in range(5):
# Generate a new element
new_element = i ** 2

# Append the new element to the array
my_array = np.append(my_array, new_element)

# Print the resulting array
print(my_array)
``````

Output:

In this example, the loop iterates from 0 to 4. For each iteration, the square of the loop index `i` is calculated and stored as the new element. Then, `numpy.append()` is used to append the new element to the existing array `my_array`. Finally, the resulting array is printed, which shows the elements that have been appended in each iteration.

Keep in mind that using `numpy.append()` in a loop can be inefficient for large arrays because it creates a new array at each iteration. If the size of the array is known in advance, it is generally more efficient to preallocate the array and update its values within the loop.

Do comment if you have any doubts or suggestions on this NumPy Array topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.