ScreenshotNeo

BlogGuides

Python len() Function: Syntax, Examples, and Use Cases

Learn what Python’s len() returns, which objects support it, and how to use it for strings, collections, custom classes, and everyday checks.

By the ScreenshotNeo team30 September 20267 min read

Python len() Function: Syntax, Examples, and Use Cases

Python’s len(value) returns the number of items in a sized object. Use it with strings, lists, tuples, dictionaries, sets, and other objects that provide a length. For a dictionary, the result is the number of keys or entries, not the total number of values nested inside it.

The syntax is a call to the built-in function, with the object passed as its positional argument:

count = len(value)

For example:

print(len("Python"))
print(len(["red", "green", "blue"]))
print(len({"name": "Ada", "age": 36}))

These calls produce 6, 3, and 2. The official Python reference describes len as returning the length, or number of items, of an object. See the Python built-in functions reference and the Python data model reference.

1. What does len() do in Python?

len() asks an object for its size and returns an integer representing its number of items. The meaning of an “item” depends on the object: a string is measured in string elements, a list in list entries, and a dictionary in key-entry pairs.

It does not recursively count everything contained by an object. A list with three inner lists has length three, regardless of how many elements those inner lists contain:

matrix = [[1, 2], [3, 4], [5, 6]]
print(len(matrix))       # 3 outer items
print(len(matrix[0]))    # 2 items in the first inner list

Likewise, a dictionary with two keys has length two even if one of its values is itself a long list. To count nested contents, write the traversal that matches the structure you intend to measure.

2. How do I use the len() function?

Pass one sized object to len(). The current Python 3.14 documentation gives the signature as len(object, /); the slash means the argument is positional-only. The ordinary form is simply len(value).

name = "Ada"
scores = [91, 88, 96]
record = {"name": name, "scores": scores}

print(len(name))       # 3
print(len(scores))     # 3
print(len(record))     # 2

len() is a built-in function, not a method. Write len(scores), not scores.len(). The function works with any object whose type provides length behavior; third-party types should be checked against their own documentation.

3. Which Python types support len()?

Common built-in sized objects include the following. These examples show the kind of units each call counts.

len() counts the top-level items defined by each object: string elements, collection entries, or dictionary keys.
len() counts the top-level items defined by each object: string elements, collection entries, or dictionary keys.
Type What len() counts Example
str String elements len("hello") → 5
bytes Bytes len(b"abc") → 3
list List entries len([4, 8]) → 2
tuple Tuple entries len((4, 8)) → 2
range Values in the range len(range(5)) → 5
dict Keys/entries len({"a": 1}) → 1
set Set members len({"a", "b"}) → 2
frozenset Frozen set members len(frozenset({1, 2})) → 2

These categories are listed in the official built-in functions reference. An arbitrary iterable is not necessarily sized. For instance, a generator can produce values without storing a known count; do not assume that every object you can loop over accepts len(). If you need to count values from a one-pass iterator, iterating through it consumes it.

4. Examples for strings, lists, tuples, dictionaries, and sets

Get the length of a string

language = "Python"
character_count = len(language)
print(character_count)  # 6

This is the length Python reports for the string. It is not necessarily the count of user-perceived characters for every Unicode text: some visible characters can be represented by multiple string elements. When an application needs a user-facing character count, define that requirement explicitly and use a Unicode-aware approach suited to it.

A call to len() reports the outer collection size; counting nested contents requires looking inside it.
A call to len() reports the outer collection size; counting nested contents requires looking inside it.

Get the number of items in a list or tuple

colors = ["red", "green", "blue"]
point = (10, 20)

print(len(colors))  # 3
print(len(point))   # 2

The count is the number of top-level entries. It is independent of what those entries contain.

Can I use len() on a dictionary?

Yes. len(dictionary) returns the number of dictionary keys, equivalently the number of entries. It does not count the contents of the values.

person = {
    "name": "Ada",
    "languages": ["Python", "Lisp", "C"]
}

print(len(person))                 # 2 keys
print(len(person["languages"]))    # 3 languages

Count set members

unique_ids = {12, 19, 24}
print(len(unique_ids))  # 3
print(len(set()))       # 0

For a set, the count is the number of members in the set.

5. Use len() for empty checks and reporting

A common use is checking whether a collection has any items. You can compare the length to zero:

if len(items) == 0:
    print("No items")
else:
    print(f"Found {len(items)} items")

For ordinary Python containers, the idiomatic emptiness check is usually if not items:

if not items:
    print("No items")

This works because a sized object with length zero is false in a Boolean context when it does not define its own __bool__() method. The data model documents this behavior. If you need to display the count, call len(items) and keep the result when you will use it more than once:

item_count = len(items)
print(f"Imported {item_count} items")

6. Define length for your own class

A custom class can support len() by defining __len__(self). The method should return a nonnegative integer. A useful implementation typically delegates to an internal collection that already knows its size.

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

An empty queue with no custom __bool__() method is false because its length is zero:

empty_queue = Queue([])
print(len(empty_queue))  # 0
print(bool(empty_queue)) # False

This behavior is specified by Python’s data model documentation. Do not return a float or a negative value from __len__(); the length protocol represents a count of zero or more items.

7. Complete runnable example

Save this as length_examples.py and run it with Python 3:

class Queue:
    def __init__(self, items):
        self.items = list(items)

    def __len__(self):
        return len(self.items)


def describe(label, value):
    print(f"{label}: {len(value)}")


def main():
    describe("string characters", "Python")
    describe("list items", ["red", "green", "blue"])
    describe("tuple items", (10, 20))
    describe("dictionary entries", {"name": "Ada", "age": 36})
    describe("set members", {"north", "south"})

    queue = Queue(["first", "second"])
    describe("queue items", queue)

    if not Queue([]):
        print("empty queue")


if __name__ == "__main__":
    main()

The output reports counts for each object and identifies the empty queue. The describe function accepts objects with length support; passing an unsized object is outside its intended input contract.

8. Errors and edge cases

  • The object is an unsized iterable. Being iterable does not guarantee that an object has a known length. If the count is required, consume or otherwise measure the iterable according to the application’s needs; account for the fact that consuming a generator uses it up.
  • The value is nested. len(outer) counts only the outer entries. Call len() on a particular inner value or traverse the structure to count a different quantity.
  • A custom length is invalid. Ensure __len__() returns a nonnegative integer, and make its count agree with the class’s definition of its items.
  • The reported size seems surprising for text. len() reports the string’s Python-level length, which may differ from the number of visible grapheme clusters in some Unicode text. Choose a suitable text-counting method if the product requirement is about visible characters.
  • The size is extremely large. The Python 3.12 built-in reference identifies an OverflowError for lengths larger than sys.maxsize as a CPython implementation detail, with range(2 ** 100) as an example. Preserve the CPython qualification; do not treat this note as a promise about every Python implementation.

9. Performance, reliability, and cost

For built-in containers, use len() directly when you need the size; it is the standard interface for that question and avoids manually counting through the container. A custom class should provide a length that reflects its actual items and can be determined reliably. If computing the count requires expensive work, consider whether the class can maintain an accurate count as its contents change; correctness matters more than caching a stale value.

Calling len() has no service cost or network requirement. Its practical limitation is the object’s own length support and the meaning of the count it reports. For one-pass iterators, counting by iteration consumes values, so plan for that side effect.

10. Capture a live example with ScreenshotNeo

If you are documenting a Python example on a live tutorial page, ScreenshotNeo can capture the page as an image or PDF. It is a website screenshot API and MCP server from ScreenshotNeo. A single GET request returns a screenshot or PDF; the API also supports full-page capture, CSS selectors, device presets, custom waits, and other capture options. The API documentation lists the request configuration.

Or skip the browser setup

Use this one-call example to save a WebP screenshot of a page:

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://docs.python.org/3/"},
    timeout=90,
)
open("python-docs.webp", "wb").write(r.content)

ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits cost nothing, with verdict and billing details in response headers. Its MCP server lets AI agents use screenshot tools, and the free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month, no card required.

11. Frequently asked questions

Is len() a function or a method?

It is a built-in function. Pass the object as an argument: len(value).

Does len() start counting at zero?

No. It returns a count. A collection with no items has length zero; one item has length one.

Can len() count values in a dictionary?

It counts dictionary entries, which correspond to keys. To count items inside a value such as a list, pass that value to len() separately.

Can every object use len()?

No. The object’s type must provide length behavior. Some iterables, including generators, do not represent a stored size that can be retrieved this way.

What should __len__() return?

A nonnegative integer representing the number of items in the custom object, as described by the Python data model.