Skip to content
Tutorials Center
My learning

Topics

Python Reference Β· Built-in Functions

Python len() function

Reference for Python len(): count the items in a string, list, tuple, dict, set or range, what it returns for nested data, and how to support it in your classes.

The len() function returns the number of items in an object: characters in a string, elements in a list or tuple, keys in a dictionary, members of a set, or values in a range. It works on anything that has a size, and it only counts the top level.

For built-in containers len() is fast because the size is stored, not counted on demand. Your own classes can support it by defining __len__().

Python
print(len("hello"))        # 5
print(len([1, 2, 3]))      # 3

Try it

Python Counting different objects

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Strings, bytes and your own classes

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
len(s)
Name Description
s A sequence (string, bytes, tuple, list, range) or a collection (dict, set, frozenset), or any object with __len__().

Return value: a non-negative int.

Raises: TypeError if the object has no length (numbers, None, iterators, generators). OverflowError is possible if __len__() returns a value larger than sys.maxsize.

Usage notes

  • Top level only. len([[1, 2], [3]]) is 2, not 3. Count nested items with a comprehension or sum().
  • Characters, not bytes. len("Γ©") is 1 Unicode code point. Encode first to count bytes: len(s.encode("utf-8")). A visible "character" made of combining marks may be several code points.
  • Dictionaries report the number of keys. Duplicate keys can't exist, so len({"a": 1, "a": 2}) is 1.
  • Truthiness. Containers with len() == 0 are false. Write if items: instead of if len(items) > 0:.
  • Iterators have no length. To count items of a generator, consume it (sum(1 for _ in gen)) or convert it to a list first, which uses memory.
  • Your classes. Define __len__() returning a non-negative integer (see __len__() and __getitem__()). A negative result raises ValueError.
  • Index relationship. The last valid index of a sequence is len(seq) - 1; negative indexes like seq[-1] are usually simpler.