Master Code
On The Go

Learn. Practice. Build.

Home › Code Snippets › Python › Reference › len()

Python Reference

len()

Return the number of items in a sequence. Works on strings, lists, dicts, and more.

Last updated: October 2026

Definition: len() returns the number of items in an object. It works on strings, lists, tuples, dicts, sets, and any object that implements the __len__() method.

🎬 Live Example

Five common len patterns. Click any button to see the output.

Input:

                
Output:

            

💡 len() is O(1) — it reads a cached value, not counts items.

📝

Basic Syntax

len(s)

# s — any object with a __len__() method
# Returns: int (number of items)
# Raises: TypeError if object has no length

🎯 Works On

Type Returns Example
strCharacter countlen("abc") → 3
listElement countlen([1,2,3]) → 3
tupleElement countlen((1,2)) → 2
dictKey-value pairslen({"a":1}) → 1
setUnique elementslen({1,2,3}) → 3
1

String Length

len("Hello")           # 5
len("")                # 0
len("Hello, World!")   # 13
len("café")            # 4 (Unicode code points)
2

List and Tuple Length

len([1, 2, 3])              # 3
len([])                     # 0
len([1, [2, 3], 4])         # 3 (nested list counts as 1)
len((1, 2, 3))              # 3

Pro tip: len() does not count nested items — a list containing a list has length 2, not 3+.

3

Dictionary Length

d = {"a": 1, "b": 2, "c": 3}
len(d)  # 3 (keys)

empty = {}
len(empty)  # 0
4

Empty Check Idiom

items = []

# ✅ Pythonic
if not items:
    print("Empty")

# ✅ Also works
if len(items) == 0:
    print("Empty")

# ❌ Don't do this
if items == []:
    print("Empty")
5

Real-World: Pagination

items = list(range(100))
page_size = 10

total_pages = (len(items) + page_size - 1) // page_size
# 10

# Check if there's a next page
def has_next(page):
    return page * page_size < len(items)

🎯 len vs count vs sum

Method Returns Use when
lenTotal itemsYou need the size
list.countOccurrences of valueYou need frequency of a value
sumSum of valuesYou need total, not count

⚠️ Common Mistakes

❓ Frequently Asked Questions

What does len() do in Python?

len() returns the number of items in an object. It works on strings, lists, tuples, dicts, sets, and any object that implements __len__().

Does len() work on numbers?

No. len() raises TypeError on int, float, and complex numbers because they have no length. Convert to a string first: len(str(42)).

How does len() work on strings?

len() returns the number of Unicode code points (characters) in the string. Emojis count as multiple code points in some cases.

How does len() work on dicts?

len() returns the number of key-value pairs. A dict with 3 keys has len() == 3, regardless of key or value sizes.

Is len() O(1) or O(n)?

len() is O(1) for all built-in types. Python stores length internally, so it just reads a cached value.

🎯 What's Next?

← All Python Reference