w3resource

NumPy: Create a null vector of size 10 and update sixth value to 11


Null Vector (10) & Update Sixth Value

Write a NumPy program to create a null vector of size 10 and update the sixth value to 11.

Python NumPy: Create a null vector of size 10 and update sixth value to 11

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a NumPy array 'x' filled with zeros of length 10
x = np.zeros(10)

# Printing the initial array 'x' filled with zeros
print(x)

# Modifying the sixth value (index 6, considering zero-based indexing) of the array to 11
print("Update sixth value to 11")
x[6] = 11

# Printing the updated array 'x' after modifying the sixth value
print(x)

Sample Output:

[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]                               
Update sixth value to 11                                                
[  0.   0.   0.   0.   0.   0.  11.   0.   0.   0.]

Explanation:

In the above code -

np.zeros(10): Creates a one-dimensional NumPy array of length 10, with all elements initialized to 0.

x[6] = 11: Sets the 7th element of the NumPy array (at index 6, since Python uses zero-based indexing) to the value 11.

print(x): Prints the modified NumPy array.

Python-Numpy Code Editor: