How to Fill Array With Value in NumPy

Muhammad Maisam Abbas Feb 02, 2024
  1. Fill Array With Value With the numpy.full() Function
  2. Fill Array With Value With the numpy.fill() Function
  3. Fill Array With Value With the for Loop in Python
How to Fill Array With Value in NumPy

This tutorial will introduce how to fill an array with values in NumPy.

Fill Array With Value With the numpy.full() Function

The numpy.full() function fills an array with a specified shape and data type with a certain value. It takes the shape of the array, the value to fill, and the data type of the array as input parameters and returns an array with the specified shape and data type filled with the specified value. See the following code example.

import numpy as np

array = np.full(5, 7)
print(array)

Output:

[7 7 7 7 7]

In the above code, we filled the value 7 inside an array of length 5 with the np.full() function. We initialized the NumPy array with identical values by specifying the shape of the array and the desired value inside the np.full() function.

Fill Array With Value With the numpy.fill() Function

We can also use the numpy.fill() function to fill an already existing NumPy array with similar values. The numpy.fill() function takes the value and the data type as input parameters and fills the array with the specified value.

import numpy as np

array = np.empty(5, dtype=int)

array.fill(7)
print(array)

Output:

[7 7 7 7 7]

We first created the NumPy array array with the np.empty() function. It creates an array that contains only 0 as elements. We then filled the array with the value 7 using the array.fill(7) function.

Fill Array With Value With the for Loop in Python

We can also use the for loop to allocate a single value to each element of an array in Python. We can first create the array using the numpy.empty() function by specifying the shape of the array as an input parameter to the numpy.empty() function. We can then allocate the desired value to each index of the array by using a for loop to iterate through each array element.

import numpy as np

array = np.empty(5, dtype=int)

for i in range(5):
    array[i] = 7
print(array)

Output:

[7 7 7 7 7]

We first created the NumPy array array by specifying the shape of the array as an input parameter inside the numpy.empty() function. As discussed in the previous example, this creates an array of the specified shape and fills each array element with a 0 value. We then used a for loop to iterate through each index of the array and explicitly specified each value to be equal to 7.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn