Methods to Create NumPy Array


In this article we are going to learn Methods to Create NumPy Array that includes like identity(),full() and full_like().We will learn each method with examples.

so let us start our article for today and start learning about these functions.

1. numpy.identity() function

The first function which we are going to learn today is numpy.identity().
This function helps us in the creation of an identity array. The identity
array is a square array with ones on the main diagonal.

The syntax for this function is:

import numpy as np

numpy.identity(n, dtype=None)


  • n: Number of rows (and columns) in n x n output.
  • dtype :data-type, which is an optional parameter. The default is float.

n x n array with its main diagonal set to one, and all other elements as 0.

Now let us understand this with an example:

print("Array Created by identity function: ",np.identity(3))

This will create an array of size 3×3 with diagonal elements as 1 and rest all
elements as 0.


Array Created by identity function: [[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

2. numPy.full() function

The next function that we are going to learn today is numpy.full. This function helps us to create an array of given shape and data type. Also, we can fill the elements of the desired value.
Let us check the syntax of this function:

numpy.full(shape, fill_value, dtype=None, order='C')


  • Desired Shape of the new array, e.g., (2, 3) or 2.
  • Fill value is the value that we want to put as all elements.
  • dtype data-type, is optional
  • order{‘C’, ‘F’}, is optional , Whether to store multidimensional data in
    C- or Fortran-contiguous (row- or column-wise) order in memory.

Here is an example of full() function.

print("full array with value inf: ",np.full((2, 2), np.inf))
print("full array with value 5: ",np.full((3, 3), 5))
print("full array with value [1,4]: ",np.full((2, 2), [1, 4]))


full array with value inf: [[inf inf]
 [inf inf]]
full array with value 5: [[5 5 5]
 [5 5 5]
 [5 5 5]]
full array with value [1,4]: [[1 4]
 [1 4]]

3. numPy.full_like() function

We have one more function that can help us create an array. This function is full_like(). This function accepts an array and creates an array of the same size, shape, and properties.
Also, this function accepts the fill value to put as all elements value.

inputarray = np.arange(4, dtype=int)
print(" full_like array with value 2: ",np.full_like(inputarray, 2))
# The fill value is float but since the input array have dtype as int so the resulting
#array will have int values only.
print(" full_like array with value 2.2: ",np.full_like(inputarray, 2.2))
# If we want to get the float values then we will need to specify the dtype.
print(" full_like array with value 3.5: ",np.full_like(inputarray, 3.5, dtype=np.double))


full_like array with value 2: [2 2 2 2]
full_like array with value 2.2: [2 2 2 2]
full_like array with value 2: [3.5 3.5 3.5 3.5]