Borislav Hadzhiev
Tue Jun 14 2022·2 min read
Photo by Adi Constantin
Use the len()
function to get the length of an array, e.g. len(my_array)
.
The len()
function returns the length (the number of items) of an object and
can be passed a sequence (an array, a list, string, tuple, range or bytes) or a
collection (a dictionary, set, or frozen set).
# 👇 get length of a list my_list = ['a', 'b', 'c'] result_1 = len(my_list) print(result_1) # 👉️ 3 # 👇️ get length of list inside of a list my_2d_list = [['a', 'b'], ['c', 'd']] result_2 = len(my_2d_list[0]) print(result_2) # 👉️ 2
If you need to get the length of a numpy
array, scroll down to the next code
snippet.
The len() function returns the length (the number of items) of an object.
The first example shows how to get the number of items in the list.
If you need to get the number of elements in a numpy
array, use the size
attribute on the array.
import numpy as np arr = np.array([1, 2, 3]) print(arr.size) # 👉️ 3 print(arr.shape) # 👉️ (3, ) my_2d_arr = np.array([[1, 2, 3], [4, 5, 6]]) print(my_2d_arr.size) # 👉️ 6 print(my_2d_arr.shape) # 👉️ (2, 3)
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 array in the example is a one-dimensional array containing 3 elements.
The first value in the tuple is the number of rows, and the second - the number of columns in the array.
You can also use the len()
function to check if a list is empty.
my_list = [] if len(my_list) == 0: # 👇️ this runs print('list is empty') else: print('list is not empty')
If a list has a length of 0
, then it's empty.
You might also see examples online that check whether the list is truthy (to check if it contains at least 1 item), which is more implicit.
my_list = [] if my_list: print('list is NOT empty') else: # 👇️ this runs print('list is empty')
All values that are not truthy are considered falsy. The falsy values in Python are:
None
and False
.0
(zero) of any numeric type""
(empty string), ()
(empty tuple), []
(empty list), {}
(empty dictionary), set()
(empty set), range(0)
(empty
range).Notice that an empty list is a falsy value, so if the list is empty, the else
block is ran.
If you need to check if the list is empty using this approach, you would negate
the condition with not
.
my_list = [] if not my_list: # 👇️ this runs print('list is empty') else: print('list is NOT empty')