Get the length of a 2D Array in Python

avatar

Borislav Hadzhiev

Tue Jun 14 20222 min read

Get the length of a 2D Array in Python #

To get the length of a 2D Array in Python:

  1. Pass the entire array to the len() function to get the number of rows.
  2. Pass the first array element to the len() function to get the number of columns.
  3. Multiply the number of rows by the number of columns to get the total.
main.py
my_arr = [[1, 2, 3], [4, 5, 6]] rows = len(my_arr) print(rows) # 👉️ 2 cols = len(my_arr[0]) print(cols) # 👉️ 3 total_elements = rows * cols print(total_elements) # 👉️ 6

If you need to get the length of a numpy array, scroll down to the next section.

The len() function returns the length (the number of items) of an object.

The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

We first passed the entire list to the len() function to get the number of rows (the number of nested lists).

Assuming that each nested list has the same number of elements, we can get the length of a column by accessing a nested list and passing the result to the len() function.

You can get the total number of items in the 2D list by multiplying the number of rows by the number of columns.

If the nested lists may be of different sizes, use the sum() function.

main.py
my_arr = [[1, 2, 3], [4, 5, 6, 7, 8]] result = sum(len(l) for l in my_arr) print(result) # 👉️ 8

The sum function takes an iterable, sums its items from left to right and returns the total.

We pass each nested list to the len function and calculate the sum.

If you need to get the length of a 2D numpy array, use the shape attribute.

main.py
import numpy as np my_2d_arr = np.array([[1, 2, 3], [4, 5, 6]]) print(my_2d_arr.shape) # 👉️ (2, 3) print(my_2d_arr.size) # 👉️ 6 rows, cols = my_2d_arr.shape result = rows * cols print(result) # 👉️ 6

The size attribute returns the number of elements in the numpy array.

The shape attribute returns a tuple of the array's dimensions.

The first value in the tuple is the number of rows, and the second - the number of columns in the array.

The two-dimensional array contains 2 nested arrays with 3 elements each.

Use the search field on my Home Page to filter through my more than 1,000 articles.