len()
The number of items in a container — characters, elements, keys or members.
Common call
len(items)
Returns
int ≥ 0
Replaces
O(1) for built-in containers — the size is stored, not counted
Watch out
numbers and generators have no len()
len(objobj — Any object implementing __len__: str, list, tuple, dict, set, bytes, range, and most containers.type: sized · required)
→ int
Demo
Live evaluation
Try:
Inputs
stringstrtext to measure
Output
'hello world'.len()
11
For a string, len counts characters (Unicode code points) — spaces included. The same call works on lists, dicts, sets and every other sized container.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| obj | sized | yes | Any object implementing __len__: str, list, tuple, dict, set, bytes, range, and most containers. |
Return value
int — The number of items: characters of a str, elements of a list/tuple, keys of a dict, members of a set.
Common patterns
Emptiness — the idiomatic way
Containers are falsy when empty; explicit len is for when the number matters.
if not items: # idiomatic empty check return if len(items) > 100: # actual size logic paginate()
Validation
Length bounds on user input.
if not 3 <= len(username) <= 20: raise ValueError("3-20 characters")
Progress denominators
Total count for percentage displays.
print(f"{i}/{len(tasks)} done")
Examples
1. String length
len("hello")
Returns
52. List length
len([1, 2, 3])
Returns
33. Dict counts keys
len({"a": 1, "b": 2})
Returns
24. Empty container
len("")
Returns
0Pitfalls
1. Numbers have no length
len works on containers, not scalars — convert first if you mean digits.
Raises
len(12345)
TypeError: object of type 'int' has no len()
Fix
len(str(12345))
5
2. Generators have no length
A generator does not know its size without being consumed.
Raises
len(x*2 for x in nums)
TypeError: object of type 'generator' has no len()
Count by consuming
sum(1 for _ in gen)
the count (generator is now exhausted)
3. len counts code points, not bytes or glyphs
Encoded size differs, and some emoji are several code points.
Not bytes
len("café")
4
Byte length
len("café".encode("utf-8"))
5
When to use
Use it
- The actual count matters (limits, pagination, progress)
- Any sized container — one spelling for all of them
Reach for something else
- Just checking emptiness → if not items:
- Counting a generator → sum(1 for _ in gen)
- Byte size of text → len(s.encode())
Notes
Complexity
O(1) for built-in containers — size is stored
Return
int ≥ 0
CPython impl
Python/bltinmodule.c → PyObject_Size → __len__ slot
Memory
No allocation
Thread-safe
Yes — a single read
FAQ
Uniformity — one spelling works across every sized type. Under the hood len(x) calls type(x).__len__(x), so it is still customizable per class.
History
1.0
One of the original built-ins.