Python len() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Built-in

Definition

In Python, len(obj) returns the number of items in a container: characters in a string, elements in a list or tuple, keys in a dict, members of a set, or numbers in a range. It always returns a non-negative int.

len() calls the object's __len__() method, so your own classes can support it. Built-in containers store their size, so len() is instant even for huge lists.

len() is a built-in function: it lives in the builtins module, so it is always available without an import.

Syntax

Pass one sized object.

python
count = len(container)
CallWhat it does
len("hello")Returns 5.
len([1, 2, 3])Returns 3.
len({"a": 1})Returns 1 (number of keys).
len(range(0, 100, 10))Returns 10.

To test for emptiness, if items: is more idiomatic than if len(items) > 0:.

Library declarations
python
len(s, /)
# calls type(s).__len__(s)

Parameters

ParameterDescription
sRequired. A sequence (str, bytes, list, tuple, range) or collection (dict, set, ...) or any object with __len__().

Return Value

Return ValueDescription
intThe number of items (0 or more).

Python Examples

Example 1 — Length of Strings, Lists, Dicts, and Ranges

Measure the most common built-in containers, including empty ones.

python
print(len("hello"))
print(len([1, 2, 3]))
print(len({"a": 1, "b": 2}))
print(len(range(0, 100, 10)))
print(len(""), len([]), len(set()))

How It Works

  1. Characters. "hello" has five characters.
  2. Items and keys. A list counts its elements; a dict counts its keys.
  3. Ranges without lists. range(0, 100, 10) holds 10 numbers, computed without generating them.
  4. Empty is zero. Empty strings, lists, and sets all have length 0.

Example 2 — Characters vs Bytes and Nested Lists

Compare a word's length with its encoded size, and count rows and items in a nested list.

python
word = "caf\u00e9"
print(len(word), len(word.encode("utf-8")))

nested = [[1, 2], [3, 4, 5], []]
print(len(nested))
print([len(row) for row in nested])
print(sum(len(row) for row in nested))

How It Works

  1. Code points, not bytes. "café" has 4 characters, but é takes 2 bytes in UTF-8, so the encoded form has 5.
  2. Outer length only. len(nested) counts the three inner lists, not the numbers inside them.
  3. Per-row lengths. A comprehension applies len() to each row.
  4. Total items. sum() of the row lengths counts all five numbers.

Example 3 — Support len() in Your Class, and What Has No Length

Give a card deck a length, then try len() on an int and a generator.

python
class Deck:
    def __init__(self):
        self.cards = [rank + suit for suit in "SH" for rank in "AKQ"]

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


deck = Deck()
print(len(deck), deck.cards[:3])

for thing in [42, (n for n in range(3))]:
    try:
        len(thing)
    except TypeError:
        print(type(thing).__name__, "has no len()")

How It Works

  1. Six cards. Two suits times three ranks build the list AS, KS, QS, AH, KH, QH.
  2. __len__ hook. len(deck) calls Deck.__len__, which reports 6.
  3. Numbers have no size. An int is not a container, so len(42) raises TypeError.
  4. Generators are lazy. A generator does not know how many items it will produce; count with sum(1 for _ in gen) if needed.

Frequently Asked Questions

Call len(my_list). It returns the number of items.
Python uses a built-in function that calls the object's __len__ method. This keeps one consistent spelling for every container.
len() counts characters (code points). Use len(text.encode("utf-8")) for the byte count.
Generators have no length. Convert with list() first, or count with sum(1 for _ in gen), which consumes it.
No. Built-in containers store their size, so len() takes the same short time for any size.

Next: list()

Build a new list from any iterable.

list() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful