How to Get Array Dimension in Python [NumPy]

Here’s an insight into how to get array size and dimension in Python. You might aware that you can create arrays from NumPy library. Below examples use the NumPy.

Python Array dimension

What is an array

An array is a set of consecutive memory locations used to store data. Each array’s item is called an element. The number of elements in the array denotes dimension.

How to create one and two dimensional arrays

import numpy as np
list1 = [1,2,3,4,5]
print(list1)
#Positions are 0,1,2,3,4
arr1  = np.array([[1,2,3,4,5]])
print(arr1) # single dimension array
list2 = [(1,2,3),(4,5,6)]
print(list2)
arr2  = np.array([[1,2,3],[4,5,6]]) # Two dimensional array
print(arr2)
How to Know Array Dimension in Python

Python array size (Dimension and shape)

Python’s shape function provide you shape and dimension. From the list you can get array dimension.

  • In the first list, you can see only one set of elements. So it’s a single-dimension array.
  • In the second list, you can see two sets of elements. So it’s a two-dimensional array.
  • According to [NumPy documentation], in the definition, you can specify the type of elements present in the array.

Array shape

Below, you will find the dimension and size of the array. The first letter in (2,3) is ‘2.’ So it is two dimensional array.

x = np.array([[1, 2, 3], [4, 5, 6]], np.int32)
>>> type(x)
<class 'numpy.ndarray'>
>>> x.shape
(2, 3)
>>> x.dtype
dtype('int32')
Array dimension innumpy
Python’s shape function to know size and dimension of an array

How to find number of elements in an array

By multiplying the shape values you will know. For example 2*4=8, that means the array has total eight elements.

Related

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.