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__().
print(len("hello")) # 5 print(len([1, 2, 3])) # 3
Try it
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.
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
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]])is2, not 3. Count nested items with a comprehension orsum(). - Characters, not bytes.
len("Γ©")is1Unicode 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})is1. - Truthiness. Containers with
len() == 0are false. Writeif items:instead ofif 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 raisesValueError. - Index relationship. The last valid index of a sequence is
len(seq) - 1; negative indexes likeseq[-1]are usually simpler.
Related
sum(),max(),min(),sorted(),enumerate(),range()__len__()and__getitem__()- Lessons: Lists, Strings, Dictionaries