HOWTO · Python

How to Get Length of a Python Array

This article introduces how to find the length of a Python object using the len() function or __len__() method. Learn about the differences between these two methods and how to apply them effectively in your Python programming projects. Discover practical examples and enhance your coding skills as you explore the fundamental concept of determining the size of arrays in Python.

On this page

Finding the length of a Python array or list usually takes one call to len(). It returns the number of items in a sized object, such as a list, tuple, string, dictionary, or array.array. Python’s length protocol also lets a custom class define how its instances are counted. Some iterators, including generators, are not sized, so they need a different approach.

Get a Python list’s length with len()

Pass the list to the built-in len() function. The result is an integer giving the number of elements, regardless of the values stored in the list.

Run this example:

my_list = [1, 2, 3, 4, 5]
length_of_list = len(my_list)
print(length_of_list)

This example prints the list’s item count. Use the same pattern with a list of strings, numbers, or other objects. The count is the number of elements at the outer level; if a list contains nested lists, len() does not add up the elements inside them.

Find the length of other Python objects

len() works with objects that expose a length. For a string, it returns the number of Unicode code points, not necessarily the number of user-perceived characters when a character is formed from multiple code points. For a dictionary, it counts keys. A tuple, set, bytes object, and array.array also report their number of items. For example, len("Python") gives the number of code points in that string, while len({"name": "Ada", "language": "Python"}) counts its two keys.

An object being iterable does not guarantee that it has a length. len() does not count items by walking through arbitrary iterables; it asks the object for its size. This makes it useful when the object already knows its item count, but it is not a universal way to count a stream of values. Avoid assuming that every call has the same performance characteristics: the cost depends on the object’s implementation.

Understand how len() and __len__() relate

The built-in len(obj) uses Python’s length protocol. A class commonly participates by defining the special method __len__(), which returns a non-negative integer representing the number of items in its instance. In ordinary application code, call len(obj) rather than invoking obj.__len__() directly. The built-in is the standard interface that also works with built-in types and lets Python apply its normal special-method lookup.

Here is a small custom class that stores its values in a list:

class CustomList:
    def __init__(self, elements):
        self.elements = elements

    def __len__(self):
        return len(self.elements)

my_custom_list = CustomList([1, 2, 3, 4, 5])
print(len(my_custom_list))

The class delegates its count to the contained list, and callers use the familiar len() interface. A custom implementation should keep the reported count consistent with the object’s actual contents. Defining __len__() does not make unrelated objects countable, and calling len() is not a general exception-prevention technique.

Handle objects that do not have a length

Generators and many other iterators produce values as they are consumed and do not store a total count. Calling len() on one of these unsized objects is unsupported. If you need to count every value and can consume the iterator, count its items by iterating through it:

generator = (number for number in range(5))
item_count = sum(1 for _ in generator)
print(item_count)

This approach reaches the end of the generator, so the values are no longer available from it afterward. If you need to use the values later, materialize them first with list(generator) and then call len() on that list. Materializing keeps the values in memory, so for a large or unbounded stream, choose an approach suited to the data instead of trying to compute a total in advance.

Get lengths for multiple objects with map()

To apply len() to several sized objects, pass it as the function to map(). In Python 3, map() returns an iterator, so wrap it with list() when you want to see and keep all the resulting counts together:

objects = [[1, 2, 3], ("a", "b"), "Python"]
lengths = list(map(len, objects))
print(lengths)

The resulting list contains one count for each input object, in the same order. Every object in objects must support len(); an unsized iterator among them will prevent the mapping from producing all of the requested lengths. If you only need to process each count once, you can iterate over map(len, objects) directly without constructing a list. Use the list form when you need to display, index, or reuse the complete set of counts.