# numpy.ndarray.fill () in Python

| | |

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.]] `

## Shop Learn programming in R: courses

\$ Best Python online courses for 2022

\$ Best laptop for Fortnite

\$ Best laptop for Excel

\$ Best laptop for Solidworks

\$ Best laptop for Roblox

\$ Best computer for crypto mining

\$ Best laptop for Sims 4

\$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

NUMPYNUMPY

How to convert Nonetype to int or string?

NUMPYNUMPY

How to specify multiple return types using type-hints

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

## Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method