Sunday, August 31, 2025
HomeLanguagesnumpy.ndarray.fill() in Python

numpy.ndarray.fill() in Python

numpy.ndarray.fill() method is used to fill the numpy array with a scalar value.

If we have to initialize a numpy array with an identical value then we use numpy.ndarray.fill(). Suppose we have to create a NumPy array a of length n, each element of which is v. Then we use this function as a.fill(v). We need not use loops to initialize an array if we are using this fill() function.

Syntax : ndarray.fill(value)

Parameters:
value : All elements of a will be assigned this value.

Code #1:




# Python program explaining
# numpy.ndarray.fill() function
import numpy as geek
  
a = geek.empty([3, 3])
  
# Initializing each element of the array
# with 1 by using nested loops 
for i in range(3):
    for j in range(3):
        a[i][j] = 1
  
print("a is : \n", a)    
  
  
# now we are initializing each element
# of the array with 1 using fill() function. 
a.fill(1)
  
print("\nAfter using fill() a is : \n", a)
       


Output:

a is : 
 [[ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]]

After using fill() a is : 
 [[ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]]

 

Code #2:




# Python program explaining
# numpy.ndarray.fill() function
import numpy as geek
  
a = geek.arange(5)
  
print("a is \n", a)
  
# Using fill() method
a.fill(0)
  
print("\nNow a is :\n", a)
       


Output:

a is 
 [0 1 2 3 4]

Now a is :
 [0 0 0 0 0]

 
Code #3: numpy.ndarray.fill() also works on multidimensional array.




# Python program explaining
# numpy.ndarray.fill() function
  
import numpy as geek
  
a = geek.empty([3, 3])
  
# Using fill() method
a.fill(0)
  
print("a is :\n", a)


Output:

a is :
 [[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]
RELATED ARTICLES

Most Popular

Dominic
32251 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6619 POSTS0 COMMENTS
Nicole Veronica
11792 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11841 POSTS0 COMMENTS
Shaida Kate Naidoo
6735 POSTS0 COMMENTS
Ted Musemwa
7016 POSTS0 COMMENTS
Thapelo Manthata
6689 POSTS0 COMMENTS
Umr Jansen
6707 POSTS0 COMMENTS