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:



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)
       

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)
       

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

a is :
 [[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.