The built-in len() answers one question: how many items does this object hold right now? The official docs describe it as returning the length—or number of items—of an object. You can pass a sequence such as a string, bytes, tuple, list, or range, or a collection such as a dictionary, set, or frozenset. This page walks from syntax through each common type, then edge cases (None, integers, generators), how len() differs from count(), and how custom classes hook in with __len__().
Tested on: Python 3.13.3; kernel 6.14.0-37-generic.
What is len() in Python?
len() is a built-in function. You give it one argument that supports the length protocol; Python returns an integer count. For containers you already use—list, tuple, dict, set, and strings—that count matches what you see at a glance: list elements, dict keys, set members, and characters (code points) in text. If the object is empty, the length is 0.
Python len() syntax
The call form is always a single argument inside parentheses:
len(object)object must implement a length (built-in sized types do this for you). The return value is always an integer ≥ 0.
Simple len() example
Get length of a string
text = "Hello"
print(len(text))When you run it, you should see 5—one per character in "Hello".
Get length of a list
scores = [10, 20, 30]
print(len(scores))That prints 3, the number of elements in the list.
Use len() with Python data types
len() with string
For a str, len() counts Unicode code points (what you usually treat as characters). If a glyph is built from multiple code points, the count can differ from what you see visually—compare with len(s.encode("utf-8")) when you need encoded byte length.
s = "Python"
print(len(s))You should see 6.
len() with list
items = ["a", "b", "c", "d"]
print(len(items))You should see 4.
len() with tuple
Tuples behave like lists for sizing: len() is the element count.
point = (10, 20)
print(len(point))You should see 2.
len() with dictionary
For a dict, len() is the number of keys (each key–value pair counts once).
user = {"name": "Ada", "role": "dev", "id": 42}
print(len(user))You should see 3. For a refresher on how dicts differ from lists and sets, see list vs set vs tuple vs dictionary.
len() with set
Sets store unique elements; duplicates collapse before you measure.
tags = {"python", "linux", "python"}
print(len(tags))You should see 2 because the second "python" is not stored twice.
len() with range
A range object represents a numeric sequence; len() reports how many values it would yield (it does not materialize them all).
r = range(0, 10, 2)
print(len(r))You should see 5 (the values 0, 2, 4, 6, 8). For more patterns, see range.
What does len() return for empty objects?
Empty containers are valid; their length is always 0.
Empty string
print(len(""))You should see 0.
Empty list
print(len([]))You should see 0.
Empty dictionary
print(len({}))You should see 0.
len() with nested lists and dictionaries
len() only measures the outer container unless you index into something nested.
Get length of outer list
nested = [[1, 2], [3, 4, 5], [6]]
print(len(nested))You should see 3—three inner lists, no matter how long each inner list is.
Get length of inner list
nested = [[1, 2], [3, 4, 5]]
print(len(nested[1]))You should see 3, the length of the second inner list.
Get number of dictionary keys
For nested dicts, call len() on the inner dict you care about:
data = {"meta": {"a": 1, "b": 2}, "values": [1, 2, 3]}
print(len(data))
print(len(data["meta"]))You should see 2 then 2—top-level keys, then keys inside "meta".
len() on unsupported types
These cases raise TypeError because the object is not sized in the way len() expects.
len() on integer
Numbers are scalar values, not sequences of items.
try:
len(42)
except TypeError as e:
print(type(e).__name__ + ":", e)You should see a line starting with TypeError: mentioning that int has no len. For numeric types in general, see Python numbers.
len() on None
None is a singleton, not a container.
try:
len(None)
except TypeError as e:
print(type(e).__name__ + ":", e)You should see TypeError with a message that NoneType has no len.
len() on generator
A generator expression or generator function produces values lazily; Python cannot know the total count without running it to exhaustion (and even then, infinite generators exist), so len() is not supported.
gen = (n for n in range(3))
try:
len(gen)
except TypeError as e:
print(type(e).__name__ + ":", e)You should see TypeError explaining the object has no len().
len() vs count()
len() answers “how big is the whole thing?” list.count(x) answers “how many times does x appear?”
values = [1, 2, 2, 3]
print(len(values))
print(values.count(2))You should see 4 then 2. Mixing these up changes validation, slicing, and loop bounds—pick len() for container size and .count() when you care about one repeated value.
len() with custom objects
How len() works
If you define __len__(self) on a class, instances become valid arguments to len(). Python calls your method and must receive a non-negative integer.
class Team:
def __init__(self, members):
self.members = list(members)
def __len__(self):
return len(self.members)
crew = Team(["Ann", "Bo", "Cy"])
print(len(crew))You should see 3. That mirrors how built-in types behave: len(obj) dispatches to type(obj).__len__(obj).
Common len() mistake
Returning something that is not an integer (or returning a negative length) fails at runtime.
class Broken:
def __len__(self):
return "many"
try:
len(Broken())
except TypeError as e:
print(type(e).__name__ + ":", e)You should see TypeError because __len__ must return a non-negative integer; CPython's exact message can vary, but the failure is always tied to an invalid return type or value. Another frequent bug is using a mutable default for a backing list (def __init__(self, items=[])), which shares one list across instances—initialize with None and assign self.items = list(items or []) instead.
Common mistakes with len()
- Calling
len()on scalars (int,float,bool) or onNone. - Expecting
len(generator)—uselist(gen)only if you intentionally materialize (memory cost) or track count yourself as you iterate. - Using
len()when you meant.count()on a list, or the reverse. - Measuring the outer container when you need
len(obj["inner"])for nested structures. - Implementing
__len__that returns a negative number or a non-int—Python rejects that when you calllen().
Python len() quick reference table
| You have | What len() returns |
|---|---|
str |
Number of Unicode code points (character count in typical text) |
list / tuple |
Number of elements |
dict / frozenset |
Number of keys / members |
set |
Number of distinct elements |
range |
Number of values in the sequence |
bytes / bytearray |
Number of bytes |
| Empty container | 0 |
| Custom class | Whatever non-negative int __len__ returns |
int, None, generator |
TypeError (no length) |
Summary
len() is the standard way to read the size of strings, lists, tuples, dicts, sets, ranges, and other sized built-ins; empty objects always report 0. Nested data needs an explicit subscript before len() if you want an inner length. Integers, None, and generators do not support len()—expect TypeError. For “how many times does this value appear?” use .count() on lists, not len(). Custom classes participate by implementing __len__ to return a non-negative integer.

