Creating Empty, Zeroes, and Ones Arrays

PythonPythonBeginner
Practice Now

Introduction

Arrays are a fundamental data structure in Numpy library. In this lab, we will learn how to create arrays in Numpy library using the empty, zeroes, and ones functions.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Creating an Empty Array using numpy.empty

numpy.empty is used to create an uninitialized array of specified shape and data type.

Syntax: numpy.empty(shape, dtype, order)

  • shape: Desired shape of the array.
  • dtype: Data type of the array element. Default is float.
  • order: Order of the array. Default is c-style row-major. Set to 'F' for FORTRAN-style (column-major order).

Code:

import numpy as np

## Creating an array with 4 rows and 3 columns
x = np.empty([4,3], dtype = int)
print(x)

Output:

[[206 0 0]
 [0 0 0]
 [0 0 0]
 [0 0 0]]

Creating a Zero Value Array using numpy.zeros

numpy.zeros is used to create an array of specified shape with all elements initialized as 0.

Syntax: numpy.zeros(shape, dtype, order)

  • shape: Desired shape of the array.
  • dtype: Data type of the array element. Default is float.
  • order: Order of the array. Default is c-style row-major. Set to 'F' for FORTRAN-style (column-major order).

Code:

import numpy as np

## Creating an array of dimension 3x3 with all elements initialized as 0
arr = np.zeros((3,3), dtype = int)
print(arr)

Output:

[[0 0 0]
 [0 0 0]
 [0 0 0]]

Creating a One Value Array using numpy.ones

numpy.ones is used to create an array of specified shape with all elements initialized as 1.

Syntax: numpy.ones(shape, dtype, order)

  • shape: Desired shape of the array.
  • dtype: Data type of the array element. Default is float.
  • order: Order of the array. Default is c-style row-major. Set to 'F' for FORTRAN-style (column-major order).

Code:

import numpy as np

## Creating an array of dimension 3x3 with all elements initialized as 1
arr = np.ones((3,3), dtype = int)
print(arr)

Output:

[[1 1 1]
 [1 1 1]
 [1 1 1]]

Summary

In this lab, we learned how to create arrays using the empty, zeroes, and ones functions in Numpy library. We covered the syntax, parameters, and examples for each function.

Other Python Tutorials you may like