# How to add elements to an array?

I’m inserting values in my array, but they are not adding and the code is showing an error to me.

``````import numpy as np
# Create a 2D array of zeros
array = np.zeros((5,5))
n = 3 # Generate n random indices
indices = np.random.randint(0, 5)
# Assign random values to the selected indices
for index in indices:
array[index, index] = np.random.rand()
print(array)

TypeError: 'int' object is not iterable
``````

In code, I’m trying to achieve this by creating a zero array and random array that will work as indices to me. Then, I want to use this random index array to insert values in my zeros array but it is giving error to me. Can you help me to code this? Are there any alternative solutions you have to code the same problem?

Hey @safa , you can also use random.permutation() to develop shuffled indices and then used them to insert values in array. Here is the code below for your better understanding:

There appears to be an issue in your code related to the selection of random indices. To resolve this problem, I am sharing corrected code that also meets your requirements. Please refer to the following code snippet:

The corrected code makes use of the `random.randint()` function to generate random indices within the range of `0-5` with a specified size of `(n, 2)`. Here, `n` represents the number of random indices to be generated, and the `2` value indicates that the indices must be in 2D since the original array was also 2D.