Skip to main content
Lists

How to get the length of a list in Python

Quick answer

Call len(lst). It's O(1) — the list stores its own length.

nums = [10, 20, 30, 40]
print(len(nums))  # 4

len() works on any built-in collection: list, tuple, set, dict, str, bytes, range, and even numpy arrays via __len__. It's O(1) for all of them because CPython keeps the size in a slot on the object.

A common Python-newcomer mistake is writing lst.length or lst.size — those don't exist. Python's design puts len() as a top-level function so it reads the same for every container type.

len() raises TypeError on values that don't support it (like generators and integers). If you're consuming a lazy iterator and want to count elements, sum(1 for _ in it) works but exhausts the iterator.

Variations

Count non-empty entries

words = ["", "hello", "", "world"]
count = sum(1 for w in words if w)  # 2

Generator + sum — the Python 'count matching' pattern.

Count occurrences of one value

nums = [1, 2, 2, 3, 2]
print(nums.count(2))  # 3

Only counts one specific value — O(n).

Length of a generator (exhausts it)

gen = (x for x in range(100))
count = sum(1 for _ in gen)  # 100 — but gen is empty now

Materialising with list() first is often clearer.

Practise this in your browser

Every how-to has a live lesson. Free tier, no card.

Start free →

Unlock every lesson

Pro — $12/mo, unlimited AI, cancel any time.

See Pro plans →

Get one Python lesson + one career idea every Friday

No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.

Related how-tos