Python 3 reference · Built-in Functions

Python len() Function

Return the number of items in a container: characters in a string, items in a list, keys in a dict, and so on.

Python 3 Since 3.0

Syntax

len(s)

Parameters

ParameterDescription
s A sequence (str, list, tuple, range, bytes) or collection (dict, set, frozenset).

Return value

An int of 0 or more.

Examples

Different containersTry it yourself
print(len("hello"))
print(len([1, 2, 3]))
print(len({"a": 1, "b": 2}))
print(len(range(0, 100, 10)))

Output

5
3
2
10
Characters vs bytesTry it yourself
print(len("café"), len("café".encode("utf-8")))
print(len("\U0001F600"))  # one emoji is one character

Output

4 5
1
Checking for emptyTry it yourself
items = []
if not items:  # more Pythonic than len(items) == 0
    print("empty")

Output

empty

Common mistakes

  • Generators and iterators have no length: len(x for x in range(3)) raises TypeError. Use sum(1 for _ in it) or convert to a list.
  • len() counts Unicode characters, not bytes; encode first to count bytes.

Version history

VersionChange
Python 3.0Added