Python len() Function

Learn Python len() function with simple examples. Get the length of strings, lists, tuples, dictionaries, sets, ranges, and custom objects, and fix common TypeError mistakes.

Published

Updated

Read time 6 min read

Reviewed byDeepak Prasad

Python len() Function

The built-in len() answers one question: how many items does this object hold right now? The official docs describe it as returning the length—or number of items—of an object. You can pass a sequence such as a string, bytes, tuple, list, or range, or a collection such as a dictionary, set, or frozenset. This page walks from syntax through each common type, then edge cases (None, integers, generators), how len() differs from count(), and how custom classes hook in with __len__().

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


What is len() in Python?

len() is a built-in function. You give it one argument that supports the length protocol; Python returns an integer count. For containers you already use—list, tuple, dict, set, and strings—that count matches what you see at a glance: list elements, dict keys, set members, and characters (code points) in text. If the object is empty, the length is 0.


Python len() syntax

The call form is always a single argument inside parentheses:

text
len(object)

object must implement a length (built-in sized types do this for you). The return value is always an integer ≥ 0.


Simple len() example

Get length of a string

python
text = "Hello"
print(len(text))
Output

When you run it, you should see 5—one per character in "Hello".

Get length of a list

python
scores = [10, 20, 30]
print(len(scores))
Output

That prints 3, the number of elements in the list.


Use len() with Python data types

len() with string

For a str, len() counts Unicode code points (what you usually treat as characters). If a glyph is built from multiple code points, the count can differ from what you see visually—compare with len(s.encode("utf-8")) when you need encoded byte length.

python
s = "Python"
print(len(s))
Output

You should see 6.

len() with list

python
items = ["a", "b", "c", "d"]
print(len(items))
Output

You should see 4.

len() with tuple

Tuples behave like lists for sizing: len() is the element count.

python
point = (10, 20)
print(len(point))
Output

You should see 2.

len() with dictionary

For a dict, len() is the number of keys (each key–value pair counts once).

python
user = {"name": "Ada", "role": "dev", "id": 42}
print(len(user))
Output

You should see 3. For a refresher on how dicts differ from lists and sets, see list vs set vs tuple vs dictionary.

len() with set

Sets store unique elements; duplicates collapse before you measure.

python
tags = {"python", "linux", "python"}
print(len(tags))
Output

You should see 2 because the second "python" is not stored twice.

len() with range

A range object represents a numeric sequence; len() reports how many values it would yield (it does not materialize them all).

python
r = range(0, 10, 2)
print(len(r))
Output

You should see 5 (the values 0, 2, 4, 6, 8). For more patterns, see range.


What does len() return for empty objects?

Empty containers are valid; their length is always 0.

Empty string

python
print(len(""))
Output

You should see 0.

Empty list

python
print(len([]))
Output

You should see 0.

Empty dictionary

python
print(len({}))
Output

You should see 0.


len() with nested lists and dictionaries

len() only measures the outer container unless you index into something nested.

Get length of outer list

python
nested = [[1, 2], [3, 4, 5], [6]]
print(len(nested))
Output

You should see 3—three inner lists, no matter how long each inner list is.

Get length of inner list

python
nested = [[1, 2], [3, 4, 5]]
print(len(nested[1]))
Output

You should see 3, the length of the second inner list.

Get number of dictionary keys

For nested dicts, call len() on the inner dict you care about:

python
data = {"meta": {"a": 1, "b": 2}, "values": [1, 2, 3]}
print(len(data))
print(len(data["meta"]))
Output

You should see 2 then 2—top-level keys, then keys inside "meta".


len() on unsupported types

These cases raise TypeError because the object is not sized in the way len() expects.

len() on integer

Numbers are scalar values, not sequences of items.

python
try:
    len(42)
except TypeError as e:
    print(type(e).__name__ + ":", e)
Output

You should see a line starting with TypeError: mentioning that int has no len. For numeric types in general, see Python numbers.

len() on None

None is a singleton, not a container.

python
try:
    len(None)
except TypeError as e:
    print(type(e).__name__ + ":", e)
Output

You should see TypeError with a message that NoneType has no len.

len() on generator

A generator expression or generator function produces values lazily; Python cannot know the total count without running it to exhaustion (and even then, infinite generators exist), so len() is not supported.

python
gen = (n for n in range(3))
try:
    len(gen)
except TypeError as e:
    print(type(e).__name__ + ":", e)
Output

You should see TypeError explaining the object has no len().


len() vs count()

len() answers “how big is the whole thing?” list.count(x) answers “how many times does x appear?”

python
values = [1, 2, 2, 3]
print(len(values))
print(values.count(2))
Output

You should see 4 then 2. Mixing these up changes validation, slicing, and loop bounds—pick len() for container size and .count() when you care about one repeated value.


len() with custom objects

How len() works

If you define __len__(self) on a class, instances become valid arguments to len(). Python calls your method and must receive a non-negative integer.

python
class Team:
    def __init__(self, members):
        self.members = list(members)

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


crew = Team(["Ann", "Bo", "Cy"])
print(len(crew))
Output

You should see 3. That mirrors how built-in types behave: len(obj) dispatches to type(obj).__len__(obj).

Common len() mistake

Returning something that is not an integer (or returning a negative length) fails at runtime.

python
class Broken:
    def __len__(self):
        return "many"


try:
    len(Broken())
except TypeError as e:
    print(type(e).__name__ + ":", e)
Output

You should see TypeError because __len__ must return a non-negative integer; CPython's exact message can vary, but the failure is always tied to an invalid return type or value. Another frequent bug is using a mutable default for a backing list (def __init__(self, items=[])), which shares one list across instances—initialize with None and assign self.items = list(items or []) instead.


Common mistakes with len()

  • Calling len() on scalars (int, float, bool) or on None.
  • Expecting len(generator)—use list(gen) only if you intentionally materialize (memory cost) or track count yourself as you iterate.
  • Using len() when you meant .count() on a list, or the reverse.
  • Measuring the outer container when you need len(obj["inner"]) for nested structures.
  • Implementing __len__ that returns a negative number or a non-int—Python rejects that when you call len().

Python len() quick reference table

You have What len() returns
str Number of Unicode code points (character count in typical text)
list / tuple Number of elements
dict / frozenset Number of keys / members
set Number of distinct elements
range Number of values in the sequence
bytes / bytearray Number of bytes
Empty container 0
Custom class Whatever non-negative int __len__ returns
int, None, generator TypeError (no length)

Summary

len() is the standard way to read the size of strings, lists, tuples, dicts, sets, ranges, and other sized built-ins; empty objects always report 0. Nested data needs an explicit subscript before len() if you want an inner length. Integers, None, and generators do not support len()—expect TypeError. For “how many times does this value appear?” use .count() on lists, not len(). Custom classes participate by implementing __len__ to return a non-negative integer.


References


Frequently Asked Questions

1. What does the Python len() function return?

It returns a non-negative integer: the number of items in a sized object (for example characters in a str, elements in a list, or keys in a dict), or zero when the object is empty.

2. Can I use len() on a generator or iterator?

No—generators and generic iterators do not support len() because their length is not known without consuming them; calling len() raises TypeError.

3. What is the difference between len() and list.count()?

len() returns how many items the whole container holds; list.count(x) counts how many times the value x appears—those numbers differ whenever elements repeat or when you only care about one value.

4. How do I make len() work on my own class?

Define len(self) on the class and return an int that represents the size; len(my_obj) calls my_obj.len() under the hood.

5. Does len() count bytes or characters for a string?

For str it counts Unicode code points (what you usually think of as characters), not encoded byte length—use len(s.encode("utf-8")) if you need byte size.
Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …