Get the length of a Python list
Use len() to count list elements, understand what nested lists count, and handle iterators that do not provide a length.
Use the built-in len() function:
items = [1, 2, 3, 4, 5]
print(len(items)) # 5
For a built-in CPython list, this reads its stored size rather than visiting every element, so the operation is constant time. It counts the outer list's elements, not every value inside nested structures.
Other objects with a length
print(len("hello")) # 5
print(len((1, 2, 3))) # 3
print(len({"a": 1})) # 1 key
print(len({1, 2, 2, 3})) # 3 distinct elements
print(len(range(10))) # 10
print(len([[1, 2], [3, 4]])) # 2 outer elements
Custom classes can implement __len__(). Their cost depends on that implementation, so the constant-time property of built-in lists should not be generalized to every object accepted by len().
Check emptiness or iterate directly
if not items:
print("The list is empty")
for index, item in enumerate(items):
print(index, item)
len(items) == 0 is also valid, but a truth check usually expresses emptiness more directly. range(len(items)) is useful when you specifically need index-based access; enumerate() gives both the index and value for ordinary iteration.
FAQ
Can I use len on a generator? No. A generator does not expose a length and raises TypeError. Count while consuming it, or materialize it if you also need to retain the values:
values = (n * n for n in range(4))
count = sum(1 for _ in values)
print(count) # 4
print(list(values)) # []; the generator was consumed
len(list(generator)) also consumes it and stores all values in memory. Neither method finishes for an infinite iterator.
Does string length count visible characters? Python strings count Unicode code points. A displayed character can contain several code points, so this is a different question from counting list elements.
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan