Skip to main content

How to Get the Length of 2D Array in Python

This guide explores various techniques for getting the dimensions and total number of elements in 2D arrays in Python, covering both standard Python lists (lists of lists) and NumPy arrays.

Getting Dimensions of a 2D Python List

A 2D list in Python is essentially a list of lists. You can find its dimensions using len() on the outer list and on one of the inner lists.

Getting the Number of Rows

The number of rows in a 2D list is the number of lists it contains and can be obtained with len() function:

my_arr = [[1, 2, 3], [4, 5, 6]]
rows = len(my_arr)
print(rows) # Output: 2

Getting the Number of Columns

The number of columns in a 2D list is the number of elements in a nested array. We can get the number of columns using len() function and the first row my_arr[0]:

my_arr = [[1, 2, 3], [4, 5, 6]]
cols = len(my_arr[0])
print(cols) # Output: 3
  • The len(my_arr[0]) will return the number of items from the first list in my_arr which represents the number of columns of the 2D list.

Getting the Total Number of Elements

  • If the number of columns is equal in each row, the total number of elements can be calculated by simply multiplying the number of rows and columns:
my_arr = [[1, 2, 3], [4, 5, 6]]

rows = len(my_arr)
cols = len(my_arr[0])
total_elements = rows * cols
print(total_elements) # Output: 6
  • If the number of columns is not equal, the number of elements can be calculated by looping through each row, and summing their lengths.
my_arr = [[1, 2, 3], [4, 5, 6, 7, 8]]
total_elements = sum(len(l) for l in my_arr)
print(total_elements) # Output: 8
  • The sum() function can be used with a generator expression (len(l) for l in my_arr) to sum the lengths of each row.

Getting Dimensions and Size of 2D NumPy Arrays

For 2D NumPy arrays, use the .shape and .size attributes.

Using .shape and .size

The .shape attribute returns the dimensions (rows, columns) of the array, while the .size attribute returns the total number of elements:

import numpy as np

my_2d_arr = np.array([[1, 2, 3], [4, 5, 6]])
print(my_2d_arr.shape) # Output: (2, 3) # Rows and columns
print(my_2d_arr.size) # Output: 6 # Total number of elements
  • The shape property returns the number of columns and rows.
  • The .size property returns the total number of elements. This is equivalent to multiplying the number of rows and columns.

Handling NumPy Arrays with Variable Length Rows

If your NumPy array contains rows of different lengths (which would have to be created with dtype=object), you can calculate the total elements with the same approach from before, using the sum() and len() to iterate through all rows:

import numpy as np

my_2d_arr = np.array([[1, 2, 3], [4, 5, 6, 7]], dtype=object)
total_elements = sum(len(arr) for arr in my_2d_arr)

print(total_elements) # Output: 7