Free tools Windows power users keep installed
One-click scans. No signup required.
Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
len(value) returns the number of items in a sized Python object. You can use it with strings, bytes, lists, tuples, ranges, dictionaries, sets, frozensets, and classes that implement __len__(). The argument is passed positionally: len(value), not value.len().
This guide explains what Python counts, how dictionaries and nested data behave, how to test for emptiness, how to define length for your own classes, and which edge cases require care.
What does len() do in Python?
Python’s built-in reference defines len() as returning “the length (the number of items) of an object.” In current Python documentation, its signature is len(object, /). The slash means the argument is positional-only, so call it as len(value).
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →The result is an integer representing items at that object’s level. For a string, those items are the string’s Python elements; for a list, they are list elements; for a dictionary, they are entries (keys). len() does not recursively count everything contained inside a nested structure.
#1 Best Overall
How do I use the len() function?
Basic syntax
len(object)
Assign the result, print it, compare it, or use it in a condition:
name = "Python"
print(len(name)) # 6
items = ["red", "green", "blue"]
if len(items) > 0:
print("The list has items")
Strings
len("Python") # 6
len("hello world") # 11
len("") # 0
The result counts elements represented in the Python string. It is not a measure of bytes in an encoding and should not be treated as a count of every visual unit a reader may perceive in complex text.
Lists and tuples
len(["red", "green", "blue"]) # 3
len((10, 20)) # 2
len([]) # 0
records = [("Ada", 36), ("Grace", 28)]
len(records) # 2
A nested list counts only its direct elements:
nested = [[1, 2], [3, 4, 5]]
len(nested) # 2
The result is two inner lists, not five numbers. To count values across all inner lists, you need an explicit operation such as a generator expression:
total_numbers = sum(len(group) for group in nested)
# 5
Bytes and ranges
len(b"ABC") # 3
len(range(10)) # 10
len(range(2, 10, 2)) # 4: 2, 4, 6, 8
A range reports how many integers it represents without requiring all of them to be stored as a list.
Can I use len() on a dictionary?
Yes. len(dictionary) returns the number of dictionary entries, which is also the number of keys. It does not add up the lengths of the values.
profile = {"name": "Ada", "age": 36}
len(profile) # 2
len({}) # 0
If a value is itself a container, measure it separately:
Rank #2
data = {
"colors": ["red", "blue"],
"tags": {"python", "code", "api"},
}
len(data) # 2 entries
len(data["colors"]) # 2 list items
len(data["tags"]) # 3 set items
Dictionary keys are unique, so assigning a new value to an existing key changes that entry rather than increasing the dictionary’s length.
Which built-in types support len()?
The Python references give these common examples:
| Type | What the result counts | Example |
|---|---|---|
str |
String elements | len("Python") == 6 |
bytes |
Bytes | len(b"ABC") == 3 |
list |
List elements | len([1, 2]) == 2 |
tuple |
Tuple elements | len((1, 2)) == 2 |
range |
Represented integer values | len(range(5)) == 5 |
dict |
Entries/keys | len({"a": 1}) == 1 |
set |
Distinct members | len({1, 2, 2}) == 2 |
frozenset |
Distinct members | len(frozenset([1, 2])) == 2 |
Third-party objects may also support len(); check their own documentation for what “item” means.
Checking whether a container is empty
Explicit comparison
items = []
if len(items) == 0:
print("No items")
This is clear when you specifically need the numeric length. You can also compare against a threshold:
if len(items) >= 3:
print("At least three items")
Python’s truth-value form
if not items:
print("No items")
For ordinary containers, the second form is idiomatic. Python’s data model specifies that when a class does not define __bool__(), an object whose __len__() returns zero is false in a Boolean context. A nonzero length is true.
Use if not items when you only need an emptiness test; use len(items) when you need the count.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
How does len() work with custom classes?
A class can implement the length protocol by defining __len__(self). The method must return an integer greater than or equal to zero.
class Queue:
def __init__(self, items):
self.items = list(items)
def __len__(self):
return len(self.items)
queue = Queue(["first", "second"])
print(len(queue)) # 2
print(bool(queue)) # True
empty_queue = Queue([])
print(bool(empty_queue)) # False
Calling len(queue) invokes the object’s __len__() method through Python’s data model. Keep the method inexpensive and consistent with the collection it represents. Do not return a float, a negative integer, or an unrelated measurement.
Length and Boolean behavior
class ResultSet:
def __init__(self, rows):
self.rows = list(rows)
def __len__(self):
return len(self.rows)
results = ResultSet([])
if not results:
print("No results")
If you need truthiness that differs from length, define __bool__() explicitly. Otherwise, the zero/nonzero result of __len__() supplies the Boolean value.
len() versus an arbitrary iterable
Not every iterable has a known size. Lists, tuples, dictionaries, and sets store or expose a size, but a generator may produce values one at a time and have no length available without consuming it.
numbers = (n for n in range(3))
# len(numbers) is not a valid way to count this generator
To count a one-use iterable, consume it deliberately:
count = sum(1 for _ in numbers)
print(count) # 3
Consumption can be expensive and may trigger side effects or exhaust the iterator. If you need repeated length checks, materialize the values when appropriate:
numbers = list(n for n in range(3))
len(numbers) # 3
Common mistakes and edge cases
Calling it as a method
Use len(value), not value.len(). The built-in dispatches to the object’s length protocol.
Counting nested contents accidentally
len([[1, 2], [3]]) is 2, because the outer list has two elements. It is not a recursive total.
Confusing dictionary keys and values
len({"a": [1, 2]}) is 1. To count the list stored under the key, call len(dictionary["a"]).
Unsupported objects
An object without a length implementation cannot provide a useful len() result. Convert it to a sized container only when doing so fits your memory and performance requirements.
Very large lengths in CPython
The Python 3.12.14 built-in reference documents a CPython-specific detail: len() raises OverflowError for lengths larger than sys.maxsize, with range(2 ** 100) as an example. This qualification applies to CPython’s documented behavior and should not be generalized to every Python implementation.
huge = range(2 ** 100)
# In CPython, len(huge) raises OverflowError because it exceeds sys.maxsize.
Practical patterns
Validate a required collection
def require_items(items):
if not items:
raise ValueError("At least one item is required")
return items
Display a count
messages = ["Build finished", "Tests passed"]
print(f"{len(messages)} messages")
Limit input size
username = "ada"
if len(username) > 30:
raise ValueError("Username is too long")
Compare two collections
if len(left) == len(right):
print("The collections have the same number of top-level items")
Equal lengths do not imply equal contents. Use equality or another comparison when values also matter.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsTroubleshooting checklist
| Symptom | Likely cause | Fix |
|---|---|---|
| The value has no usable length | The object is an unsized iterator or custom object without __len__() |
Consume it intentionally or convert it to a list when appropriate. |
| The count is smaller than expected | You counted an outer container, dictionary keys, or distinct set members | Measure the specific nested value or choose the data structure that matches your counting goal. |
| Boolean logic behaves unexpectedly | A custom class defines __bool__(), or its __len__() result is wrong |
Inspect both methods and ensure __len__() returns a nonnegative integer. |
CPython raises OverflowError |
The represented length exceeds sys.maxsize |
Handle the implementation-specific limit or use an algorithm that does not require materializing or directly requesting that length. |
Or skip the browser setup
If your Python workflow also needs a web-page screenshot, ScreenshotNeo provides a single HTTP request instead of requiring you to install and manage a browser. Before capture it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets. Bot checks, blank pages, timeouts, failed loads and cache hits are not billed as clean shots, and the response identifies the page verdict and billing status in headers.
Use the API documentation at https://screenshotneo.com/docs/ for request options:
Best Value
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
ScreenshotNeo also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 shots. Learn more at https://screenshotneo.com or sign up free.
Further reading
The official Python built-in functions reference documents len() and its supported built-in categories. The Python 3.14.7 data model reference explains __len__(), nonnegative integer results, and length-based truth testing.
Frequently Asked Questions
Does len() modify the object?
No. For standard sized containers it reports the current size; it does not remove or add items.
Is len() the same as counting an iterable with a loop?
Not always. Sized containers expose a length directly, while a generator may need to be consumed to count its values.
Can __len__() return zero for a nonempty custom object?
It can technically do so, but that would make the object appear false unless it defines __bool__(). Implement the method to reflect the collection’s documented size.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →

