Shape and Size of Array in Python

Muhammad Maisam Abbas Jan 30, 2023 Feb 28, 2021 NumPy NumPy Array
  1. Get the Shape of an Array With the numpy.shape() Function in Python
  2. Get the Size of an Array With the numpy.size() Function in Python
Shape and Size of Array in Python

In this tutorial, we will discuss methods to get the shape and size of an array in Python.

Get the Shape of an Array With the numpy.shape() Function in Python

The numpy.shape() function gives us the number of elements in each dimension of an array. numpy.shape() returns a tuple that contains the number of elements in each dimension of an array.

The following code example shows us how we can use the numpy.shape() function to get the shape of an array in Python.

import numpy

arr = numpy.array([[1, 2, 3, 4], [5, 6, 7, 8]])

print(numpy.shape(arr))

Output:

(2, 4)

In the above code, we first initialize an array arr using numpy.array() function and then get the shape of that array with numpy.shape() function.

Get the Size of an Array With the numpy.size() Function in Python

The size of an array is the total number of elements in the array. The numpy.size() function in the NumPy package returns the size of a given array. The following code example shows how we can get the size of an array using the numpy.size() function.

import numpy

arr = numpy.array([[1, 2, 3, 4], [5, 6, 7, 8]])

print(numpy.size(arr))

Output:

8

In the above code, we first initialize an array arr using numpy.array() function and then get the size of that array with numpy.size() function.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

Related Article - NumPy Array

  • Iterate Over Rows of a Numpy Array in Python
  • Python NumPy Shift Array
  • Write NumPy Array to CSV in Python
  • Convert 3D Array to 2D Array in Python