How To Get The Length Of A 2D Array In Python

To get the length of a 2D Array in Python, you can use numpy.array.size property or use len() function. Let follow the article below.

Get the length of a 2D Array in Python

The array is a data structure to store elements. The index of the array starts at 0, and the last index is equal to the number of array elements minus 1.

A two-dimensional array consisting of two elements: rows and columns.

Syntax:

[[ r1, r2, r3, .., rn ], [ c1, c2, c3, ......., cn ]]

Parameters:

• r: are the rows of the array.
• c: are the columns of the array.

Example:

myArray= [[1,2,3], [4,5,6], [7,8,9]]

Array ‘myArray’ consists of 4 rows and 5 columns.

To get the length of a 2D Array in Python, I have the following ways:

Use numpy.array.size property

In this case, I use the numpy.array.size property to find the length of a 2D array. To use it, you need to declare the Numpy library.

Example:

• Create a 2D array.
• Create arrays using numpy.
• Use the array.size function to calculate the size of the array.
import numpy as np

myArray = ([[1,2,3], [4,5,6], [7,8,9]])
numpyArr = np.array([[1,2,3], [4,5,6], [7,8,9]])

# Use the array.size to get the size of the array
print("Size of the 2D array: ", numpyArr.size)

Output:

Size of the 2D array: 9

Use len() function

To find the length of a 2D array you can use the len() function.

Syntax:

len(object)

Parameters:

• object: an object for which you want to calculate the length. That object can be a string, bytes, tuple, list, range, dictionary, set, or frozen set. Specifically, in this case, a 2-dimensional array.

The len() function returns the number of characters of the input string.

Example:

• Create 2D array.
• Use len() function to calculate the number of rows.
• Use len() function to calculate the number of columns.
• Size of 2D array = rows * columns.
myArray = [[1,2,3], [4,5,6], [7,8,9]]
rowSize = len(myArray)
columnSize = len(myArray[0])
print("Size of 2D array: ", columnSize * rowSize)

Output:

Size of 2D array: 9

Use the ‘shape’ property

Another way to find the length of a 2D array is to use the ‘numpy.shape’ property.

Example:

• Create a 2D array.
• Create arrays using numpy.
• The ‘shape’ property returns the set of dimensions of array 2D (rows and columns).
• Size of 2D array = rows * columns.
import numpy as numpy

numpyArray = numpy.array([[1,2,3], [4,5,6], [7,8,9]])
print('Number of rows and columns ', numpy.shape(numpyArray))

# The 'shape' property returns the set of dimensions of array 2D (rows and columns)
cols, rows = numpyArray.shape
lenOf2DArray = rows * cols
print("The length of 2D Array :", lenOf2DArray)

Output:

Number of rows and columns (3, 3)
The length of 2D Array : 9