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.
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)

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')

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
You must be logged in to post a comment.