Coding

len in Python: How the len() Function Works, With Examples

len() is the built-in Python function that returns the number of items in an object: len([10, 20, 30]) is 3 and len("hello") is 5. It works on sequences such as strings, lists, tuples and ranges, and on collections such as dictionaries and sets.

print(len("hello"))          # 5
print(len([10, 20, 30]))     # 3
print(len({"a": 1, "b": 2})) # 2

The Python documentation describes it as returning "the length (the number of items) of an object", where the argument "may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set)". The result is always an integer. This page covers what len() gives for each type, the common ways it fails, and how to make your own class work with it. If you want to count how often one value appears, see counting items in a list and characters in a string.

How len() works on each type

What counts as "an item" depends on the type. This table shows each case, with the result you get from the example.

TypeExampleResultWhat is counted
strlen("python")6Characters (Unicode code points)
listlen([1, 2, 2])3Elements, duplicates included
tuplelen((1, 2))2Elements
dictlen({"a": 1, "b": 2})2Keys (one per key-value pair)
setlen({1, 2, 2})2Distinct members
rangelen(range(2, 10, 2))4Values the range produces (2, 4, 6, 8)
byteslen(b"abc")3Bytes

For a range, range(start, stop, step) stops before stop, so range(2, 10, 2) produces 2, 4, 6 and 8, and len(range(5)) is 5. Running len(range(...)) is easier than counting the values in your head.

len() of a string: characters, not bytes

For a str, len() counts Unicode code points. Spaces, punctuation and newlines each count as one.

print(len("hello world"))   # 11
print(len("line one\nline two"))  # 17
print(len(""))              # 0

Code points are not the same as what a reader sees as one character, and they are not the same as bytes. These examples are easy to reproduce:

text = "é"
print(len(text))                    # 1  (one code point, U+00E9)
print(len(text.encode("utf-8")))    # 2  (two bytes in UTF-8)

decomposed = "é"              # "e" plus a combining accent
print(len(decomposed))              # 2  (looks like one letter)

If you need the size of a string when stored or sent over the network, encode it first and take the length of the bytes. If you need the number of visible characters in text that may contain combining marks or emoji sequences, len() alone can overcount, because it does not group code points.

len() of lists, tuples and dictionaries

len() counts the top level only. A list inside a list is one item, however long the inner list is.

matrix = [[1, 2], [3, 4, 5]]
print(len(matrix))        # 2
print(len(matrix[1]))     # 3

scores = {"ana": 91, "ben": 78, "cho": 85}
print(len(scores))        # 3
print(len(scores.keys())) # 3, keys(), values() and items() views also have a length

To count every number in a nested list you add up the inner lengths: sum(len(row) for row in matrix) gives 5.

Check for an empty list or string

The most common use of len() is testing whether something is empty. len(items) == 0 works, but Python also lets you test the object directly. The documentation's truth value rules list empty sequences and collections ('', (), [], {}, set(), range(0)) as false, so this is the usual idiom:

items = []

if not items:
    print("nothing to process")

if len(items) > 0:
    print("has items")

Use the explicit len() comparison when you want to be obvious about intent, or when the value could be None and you want a loud failure rather than a silent pass. not None is true, so a bare if not items treats None the same as an empty list, while len(None) raises an error.

Using len() in loops and slices

Because indexes run from 0 to len(x) - 1, the last element is x[len(x) - 1], or more simply x[-1]. When you loop with an index, range(len(x)) produces valid indexes:

names = ["ana", "ben", "cho"]

for index in range(len(names)):
    print(index, names[index])

# Usually clearer:
for index, name in enumerate(names):
    print(index, name)

Reading names[len(names)] is an off-by-one mistake and raises IndexError: list index out of range, because the last valid index is len(names) - 1. Slicing is more forgiving: names[:len(names)] returns a full copy without error.

Why you get "object of type has no len()"

Passing something without a length raises TypeError. The message names the type:

len(42)
# TypeError: object of type 'int' has no len()

len(None)
# TypeError: object of type 'NoneType' has no len()

len(x for x in range(3))
# TypeError: object of type 'generator' has no len()

Example error text; the type name in the message changes with the object. The usual causes:

  • A number where you expected a list. A function returned a count instead of the items, or you overwrote a variable. If you want the digit count of an integer, use len(str(42)), which is 2.
  • None from a function. A function with no return, or one that returns None on failure, hands None to len(). Print the value before the call to see it.
  • A generator or iterator. These produce items on demand and cannot say how many are left. Convert with len(list(generator)) if the data fits in memory, or count while looping: sum(1 for _ in generator).

How to make len() work on your own class

Define a __len__ method. Per the data model documentation, it is "called to implement the built-in function len()" and "should return the length of the object, an integer >= 0".

class Playlist:
    def __init__(self):
        self._tracks = []

    def add(self, title):
        self._tracks.append(title)

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


playlist = Playlist()
print(len(playlist))   # 0
playlist.add("Song A")
print(len(playlist))   # 1

There is a side effect worth knowing. The documentation states that an object that does not define __bool__() and whose __len__() returns zero is considered false in a Boolean context. So if playlist: is false while it is empty, and true afterwards. If you do not want that, define __bool__ as well.

Keep __len__ returning a non-negative integer, as the documentation requires.

Limits

The len() entry carries a CPython implementation note: len raises OverflowError on lengths larger than sys.maxsize, such as range(2 ** 100). You will not meet this with ordinary data, since sys.maxsize is 9,223,372,036,854,775,807 on a 64-bit build. It matters only for huge virtual objects like that range, where the object can describe more items than could ever be stored.

Frequently asked questions

What does len() return in Python?
len(x) returns the number of items in x as an integer. For a string it is the number of characters, for a list or tuple the number of elements, for a dictionary the number of keys, and for a set the number of distinct members.
Why do I get TypeError: object of type 'int' has no len()?
len() only works on objects that have a length, such as sequences and collections. An integer, a float or None has no length, so Python raises TypeError. Check that the variable holds the list or string you expect, or convert a number with str() first if you want its digit count.
Can I use len() on a generator?
No. A generator does not know how many items it will produce, so len() raises TypeError. Either build a list first with list(generator) and take its length, or count items as you loop, for example with sum(1 for _ in generator).
What is the largest value len() can return?
In CPython, the length must be at most sys.maxsize. The Python documentation says len() raises OverflowError for larger lengths, for example for range(2 ** 100).

Sources