How to Check the Length of an Array in Python

A Tucson bike shop asked me to check the length of an array in its Python report, which said six orders for two days. The fix is len(), but the script had switched to a NumPy table, where len() counts rows.

Quick answer: call len() on a list or array.array. For a NumPy array, use .size for every element and len() only for the first dimension:

len([129.99, 48.50, 312.75])   # 3
np_array.size                  # all elements

In this tutorial, I’ll check the length of an array in Python across lists, NumPy and pandas, and clear up count versus length. Every output below came from Python 3.12.5, NumPy 2.5.3 and pandas 3.0.6.

How Do You Find the Length of a Python List or array.array?

Most Python “arrays” are lists, and the built-in len() function returns how many elements they hold. The array module’s typed arrays work the same way:

from array import array

orders = [129.99, 48.50, 312.75, 64.00, 19.95]
totals = array("d", orders)      # typed array of floats

print("list length: ", len(orders))
print("array length:", len(totals))
print("empty?       ", len([]) == 0, not orders)

Output:

list length:  5
array length: 5
empty?        True False
VS Code output of Python len() returning 5 for a list and an array.array of order totals
The list and the typed array both hold 5 elements.

Both report 5 orders. Python stores the length on the object, so len() is instant, and you can test emptiness with if not orders:.

Get the Number of Elements in a NumPy Array with size and shape

Same totals as a 2 x 3 NumPy array, which is where the bike shop’s report went wrong:

import numpy as np

# two days of order totals, three orders each
week = np.array([[129.99, 48.50, 312.75],
                 [64.00, 19.95, 88.40]])

print("len:  ", len(week))       # first dimension only
print("size: ", week.size)       # every element
print("shape:", week.shape)
print("ndim: ", week.ndim)

Output:

len:   2
size:  6
shape: (2, 3)
ndim:  2
VS Code output of NumPy len, size, shape and ndim on a 2 by 3 array
len() gives 2 rows while .size counts all 6 elements.

len(week) is 2, while week.size is 6. Read the tuple in .shape as rows and columns; my NumPy shape guide goes deeper. To count only non-zero values, use np.count_nonzero().

Count Rows and Elements in pandas Series and DataFrames

Now the orders sit in a pandas DataFrame with one blank total:

import pandas as pd

df = pd.DataFrame({
    "customer": ["Emily", "Jacob", "Olivia", "Mason"],
    "total": [129.99, 48.50, None, 64.00],
})
print("len(df):   ", len(df))
print("df.shape:  ", df.shape)
print("df.size:   ", df.size)
print("Series len:", len(df["total"]))
print("count():   ", df["total"].count())   # skips NaN

Output:

len(df):    4
df.shape:   (4, 2)
df.size:    8
Series len: 4
count():    3
VS Code output of pandas len, shape, size and count on a DataFrame with one missing total
Four rows, eight cells, and three non-blank totals.

len(df) is the row count, df.size is rows times columns, and count() ignores NaN, which is why it says 3. More options are in getting the length of a pandas DataFrame.

Array Count vs Length in Python: count(), Nested Lists and Loops

If you searched for “array count”, you probably want the length. But count(x) answers a different question: how many elements equal x.

from array import array

items = array("i", [2, 1, 2, 3, 2])     # items per order
print("length:     ", len(items))
print("count of 2: ", items.count(2))

boxes = [[1, 2], [3], [4, 5, 6]]
print("nested:     ", len(boxes), sum(len(b) for b in boxes))

n = 0
for _ in items:                          # manual count
    n += 1
print("loop count: ", n)

Output:

length:      5
count of 2:  3
nested:      3 6
loop count:  5
VS Code output comparing len and count on a Python array, a nested list total and a manual loop
Length 5, the value 2 three times, and 6 items in 3 boxes.

For nested lists, len() counts the inner lists, so sum their lengths for every item. The loop only shows what len() does. See counting occurrences in Python arrays and finding the size of a Python list.

Common Errors When Checking Array Length and How to Fix Them

Four mistakes I keep seeing in beginner scripts:

orders = [129.99, 48.50, 312.75]
checks = {
    "orders.length": lambda: orders.length,
    "len(None)": lambda: len(None),
    "orders[len(orders)]": lambda: orders[len(orders)],
    "len(generator)": lambda: len(x for x in orders),
}
for label, fn in checks.items():
    try:
        fn()
    except Exception as e:
        print(f"{label:20} {type(e).__name__}: {e}")

Output:

orders.length        AttributeError: 'list' object has no attribute 'length'
len(None)            TypeError: object of type 'NoneType' has no len()
orders[len(orders)]  IndexError: list index out of range
len(generator)       TypeError: object of type 'generator' has no len()

Python has no .length, so call len(). Check for None first, use orders[-1] for the last item (indexes start at 0), and wrap a generator in list().

Next, try one of these array tutorials:

Frequently asked questions

How do I find the length of an array in Python?

Use len(arr). It works on lists, tuples, array.array and NumPy arrays.

How do I get the number of elements in a NumPy array?

Use arr.size. len(arr) returns only the size of the first dimension.

Is array count the same as array length?

No. len(arr) gives the number of elements; arr.count(x) counts how many equal x.

How do I count rows in a pandas DataFrame?

Use len(df) or df.shape[0]. df.size counts every cell.

Why does len() fail on a generator?

Generators have no stored length. Use list() first, or sum(1 for _ in gen).

Where is len() documented?

See len() in the Python docs.