Python code to find 2D array size

10400

In this article, we will learn how to find 2D array size or 2D list size using Python. We will learn how to find 2D array size using len function and using NumPy size function.

Python 2D array/list size using len function

This method will work if the length of the column size is the same i.e. the elements in each column is the same.

Steps:

  • Initialize the 2D array/list.
  • Calculate the length of column size
  • Calculate the length of row size
  • Total elements in the 2D array or list row_sizexcolumn_size

Code:

a = [[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]

column_size = len(a[0])
row_size = len(a)
print("Size of 2D array: ", row_size, "x", column_size)
print("Total number of elements: ", row_size*column_size)

Output:

Size of 2D array:  4 x 3
Total number of elements:  12

 

Python 2D array/list size using len function for varying column size

This method will work for both cases where the length of each column can be varying or the same.

Steps:

  • Initialize the 2D array/list.
  • Run the loop to calculate the size of each column size.
  • At the end of the loop, you will be able to calculate the size of the columns.
  • Total elements in the 2D array is equal to the total elements in all the columns calculated in the loop.

Code:

a = [[1], [1, 2], [3, 4, 5], [6, 7, 8]]
total_columns_size = 0
#Loop to find the size of all the columns
for i in range(0, len(a)):
    total_columns_size = total_columns_size + len(a[i])

print("Total number of elements: ", total_columns_size)

Output:

Total number of elements:  9

 

Python 2D array size using NumPy size function

Steps:

  • Initialize the 2D array/list.
  • Create the array using numpy
  • Use the size Numpy function to calculate the total size of the array

Code:

import numpy as np

a = [[1, 0, 1, 4], [1, 2, 4, 5], [1, 2, 4, 5], [1, 2, 4, 5]]
arr = np.array(a)
print("Size of the 2D array: ", arr.size)

Output:

Size of the 2D array:  16