Python Reference
len()
Return the number of items in a sequence. Works on strings, lists, dicts, and more.
Last updated: October 2026
Definition: len() returns the number of items in an object. It works on strings, lists, tuples, dicts, sets, and any object that implements the __len__() method.
🎬 Live Example
Five common len patterns. Click any button to see the output.
💡 len() is O(1) — it reads a cached value, not counts items.
Basic Syntax
len(s)
# s — any object with a __len__() method
# Returns: int (number of items)
# Raises: TypeError if object has no length
🎯 Works On
| Type | Returns | Example |
|---|---|---|
| str | Character count | len("abc") → 3 |
| list | Element count | len([1,2,3]) → 3 |
| tuple | Element count | len((1,2)) → 2 |
| dict | Key-value pairs | len({"a":1}) → 1 |
| set | Unique elements | len({1,2,3}) → 3 |
String Length
len("Hello") # 5
len("") # 0
len("Hello, World!") # 13
len("café") # 4 (Unicode code points)
List and Tuple Length
len([1, 2, 3]) # 3
len([]) # 0
len([1, [2, 3], 4]) # 3 (nested list counts as 1)
len((1, 2, 3)) # 3
Pro tip: len() does not count nested items — a list containing a list has length 2, not 3+.
Dictionary Length
d = {"a": 1, "b": 2, "c": 3}
len(d) # 3 (keys)
empty = {}
len(empty) # 0
Empty Check Idiom
items = []
# ✅ Pythonic
if not items:
print("Empty")
# ✅ Also works
if len(items) == 0:
print("Empty")
# ❌ Don't do this
if items == []:
print("Empty")
Real-World: Pagination
items = list(range(100))
page_size = 10
total_pages = (len(items) + page_size - 1) // page_size
# 10
# Check if there's a next page
def has_next(page):
return page * page_size < len(items)
🎯 len vs count vs sum
| Method | Returns | Use when |
|---|---|---|
len | Total items | You need the size |
list.count | Occurrences of value | You need frequency of a value |
sum | Sum of values | You need total, not count |
⚠️ Common Mistakes
- Calling len on integers. Raises TypeError. Convert with
str()first. - Thinking len counts nested items. It counts top-level only.
- Comparing to [] or "" for empty. Use
if not itemsinstead. - Using len in a loop to iterate. Iterate directly —
for x in items. - Assuming len returns float. It always returns int.
❓ Frequently Asked Questions
What does len() do in Python?
len() returns the number of items in an object. It works on strings, lists, tuples, dicts, sets, and any object that implements __len__().
Does len() work on numbers?
No. len() raises TypeError on int, float, and complex numbers because they have no length. Convert to a string first: len(str(42)).
How does len() work on strings?
len() returns the number of Unicode code points (characters) in the string. Emojis count as multiple code points in some cases.
How does len() work on dicts?
len() returns the number of key-value pairs. A dict with 3 keys has len() == 3, regardless of key or value sizes.
Is len() O(1) or O(n)?
len() is O(1) for all built-in types. Python stores length internally, so it just reads a cached value.