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
| Parameter | Description |
|---|---|
s |
A sequence (str, list, tuple, range, bytes) or collection (dict, set, frozenset). |
Return value
An int of 0 or more.
Examples
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
print(len("café"), len("café".encode("utf-8")))
print(len("\U0001F600")) # one emoji is one character
Output
4 5 1
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))raisesTypeError. Usesum(1 for _ in it)or convert to a list. len()counts Unicode characters, not bytes; encode first to count bytes.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
range()· Create an immutable sequence of integers from start up to (but not including) stop, in steps. Used in for loops.list()· Create a list: an ordered, changeable sequence. Called with an iterable, it copies its items into a new list.str()· Convert a value to its readable text form, or decode bytes into a string. Strings are immutable sequences of characters.sum()· Add up the numbers in an iterable, plus an optional start value. Floats are summed with extra precision since Python 3.12.- Python Lists · tutorial
- Python Strings · tutorial