Borislav Hadzhiev
Tue Jun 14 2022·2 min read
Photo by Antonina Bukowska
To get the length of a 2D Array in Python:
len()
function to get the number of rows.len()
function to get the number of
columns.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).
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.
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.
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.