  # numpy.ndarray.fill () in Python

Arrays | Loops | NumPy | Python Methods and Functions

If we need to initialize a numpy array with the same value then we use numpy.ndarray.fill (). Suppose we have to create a NumPy array of of length n, each element of which is v. Then we use this function a.fill (v). We don`t need to use loops to initialize the array if we use 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 ]) ``    # Initialize each element in the array # with 1 using nested loops for i in range ( 3 ): for j in range ( 3 ): a [i] [j] = 1   print ( "a is:" , a)       # now we initialize each element # of the array with 1 using the fill function (). a.fill ( 1 )   print ( "After using fill () a is:" , 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" ` `, a) `   ` # Using the fill () method ` ` a.fill (` ` 0 ` `) `   ` print ` ` (` ` "Now a is:" ` `, a) `

Exit:

` a is [0 1 2 3 4] Now a is : [0 0 0 0 0] `

Code # 3: numpy.ndarray.fill () also works with multidimensional arrays.

` `

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

` ` Exit :

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