len() Function in Python (With Examples)

The len() function in Python returns how many items an object holds: characters in a string, elements in a list or tuple, keys in a dictionary. It works on any sequence or collection, and it’s instant, because Python stores the size rather than counting:

len("Austin")                     # 6
len(["Austin", "Dallas"])         # 2
len({"TX": 0.0625, "CO": 0.029})  # 2 keys

Every output here comes from Python 3.12.5 in the Windows Command Prompt, with sample data built around US cities and state tax rates.

You’ll see what len() counts for each type, how Unicode text affects it, the TypeError for numbers and generators, and how to give your own classes a length.

How len() works on strings, lists, tuples, dictionaries and sets

The same function counts something different depending on what you pass in:

print(len("Austin"))                         # characters in a string
print(len(["Austin", "Dallas", "Houston"]))   # items in a list
print(len((30.27, -97.74)))                   # items in a tuple
print(len({"TX": 0.0625, "CO": 0.029}))       # KEYS in a dictionary
print(len({"TX", "CO", "TX"}))                # a set drops the duplicate
print(len(range(0, 100, 5)))                  # numbers a range would produce
print(len(""), len([]), len({}))              # empty containers

Output:

6
3
2
2
2
20
0 0 0
Command Prompt output of the Python len function on a string, list, tuple, dictionary, set, range and empty containers
A dictionary counts its keys, a set counts unique items and a range counts the numbers it would produce.
Typelen() countsGuide
strCharactersLength of a string
listItemsLength of a list
tupleItemsLength of a tuple
dictKeysLength of a dictionary
setUnique items—
rangeNumbers it would produce—
NumPy arraySize of the first dimensionLength of an array
pandas DataFrameRowsLength of a DataFrame

The range line is worth a second look: len(range(0, 100, 5)) is 20 without creating a single number. Python works it out from the start, stop and step.

len() counts characters, not bytes

For text, len() counts characters. That’s usually what you want, but it isn’t the number of bytes the text takes once it’s encoded:

city = "café"

print("characters :", len(city))
print("UTF-8 bytes:", len(city.encode("utf-8")))   # é takes two bytes

for ch in city:
    print(ch, "->", len(ch.encode("utf-8")), "byte(s)")

Output:

characters : 4
UTF-8 bytes: 5
c -> 1 byte(s)
a -> 1 byte(s)
f -> 1 byte(s)
é -> 2 byte(s)
Command Prompt output showing Python len of cafe with an accent is 4 characters but 5 bytes in UTF-8
Four characters, five bytes: the accented é needs two bytes in UTF-8.

If a database column, an API or a file format limits size in bytes, measure len(text.encode("utf-8")), not len(text). In my experience, accented names in a customer list are the classic way this bites.

len() of a nested list or dictionary

len() only looks at the top level. A list of three rows has a length of 3, however many seats each row holds:

seats = [["A1", "A2"], ["B1", "B2", "B3"], []]

print("rows:", len(seats))                          # only the outer list
print("seats per row:", [len(row) for row in seats])
print("all seats:", sum(len(row) for row in seats))

order = {"id": "A101", "items": ["mug", "pen", "ink"]}
print("keys in order:", len(order), "| items:", len(order["items"]))

Output:

rows: 3
seats per row: [2, 3, 0]
all seats: 5
keys in order: 2 | items: 3

To count everything inside, add up the lengths of the parts, as sum(len(row) for row in seats) does here.

Why do I get ‘object of type int has no len()’?

Numbers, None and generators don’t have a length, so len() raises a TypeError:

for value in [42, 19.99, None, (n for n in range(3))]:
    try:
        print(len(value))
    except TypeError as err:
        print("TypeError:", err)

print(len(str(42)))                          # digits in a number: convert first
print(len(list(n for n in range(3))))        # a generator: materialize it first

Output:

TypeError: object of type 'int' has no len()
TypeError: object of type 'float' has no len()
TypeError: object of type 'NoneType' has no len()
TypeError: object of type 'generator' has no len()
2
3
Command Prompt output of Python len raising TypeError for an int, a float, None and a generator, plus the fixes
Each TypeError names the type. Convert a number to a string, or a generator to a list, if you really need a count.

For a number, you usually want its digit count, which is len(str(n)). A generator produces values one at a time and doesn’t know how many it will make, so turn it into a list first, or count as you go.

Using len() on your own classes with __len__

Give a class a __len__ method that returns an integer, and len() works on its objects. Python also uses it to decide whether the object is truthy:

class Cart:
    def __init__(self):
        self.items = []

    def add(self, name, price):
        self.items.append((name, price))

    def __len__(self):                       # len(cart) calls this
        return len(self.items)

cart = Cart()
cart.add("Coffee mug", 12.99)
cart.add("Notebook", 4.50)

print("items in cart:", len(cart))
print("cart is empty?", not cart)            # __len__ also drives truthiness

Output:

items in cart: 2
cart is empty? False
Command Prompt output of a Python Cart class with a __len__ method so len returns the number of items
len(cart) called __len__, and an empty cart would be falsy.

__len__ must return a whole number that’s zero or more; anything else raises an error when you call len().

len() vs not: checking if a list is empty

You can test for an empty container with len(x) == 0, but I’d write the shorter not x, which is what most Python code uses:

orders = []

if not orders:                   # the idiomatic empty check
    print("no orders yet")

if len(orders) == 0:             # works too, just longer
    print("still no orders")

orders.append("A101")
print("now:", len(orders), "order(s)")

Output:

no orders yet
still no orders
now: 1 order(s)

Both work because empty containers count as false. Checking if a variable is null or empty covers strings, None and NumPy arrays, where the rules differ.

Python len() function: quick reference

QuestionCode
How many characters?len(text)
How many bytes?len(text.encode("utf-8"))
How many items or keys?len(items)
How many digits in a number?len(str(n))
Items in a nested listsum(len(row) for row in grid)
Is it empty?not items
Length of my own objectDefine __len__

Need the length of something specific? These guides go into detail:

Frequently asked questions

What does len() do in Python?

It returns the number of items in an object: characters in a string, elements in a list or tuple, keys in a dictionary, and so on.

Does len() count from 0 or 1?

It returns a count, so a list with three items has a length of 3. Indexes start at 0, which is why the last index is len(x) - 1.

What does len() return for a dictionary?

The number of keys. Use len(d.values()) for the same number from the values side.

Why does len() give an error for an integer?

Integers don’t have a length. Use len(str(n)) to count digits.

Is len() slow on a large list?

No. Built-in containers store their size, so len() takes the same time for ten items or ten million.

How do I use len() on a custom class?

Define a __len__ method that returns a non-negative integer. The len() documentation describes what it accepts.