Codectionary / Developer documentation / Python

len()

len() is a built-in function that returns the number of items in a collection - the character count of a string, the number of elements in a list or tuple, the number of key-value pairs in a dictionary, or the number of items in a set. It's one of the most frequently used built-in functions in Python, often paired with range() or comparisons to control loops and validate data.

Syntax

len(object)

Examples

Length of Different Collections

Using len() across strings, lists, dictionaries, and more.

print(len("Hello"))              # 5
print(len([1, 2, 3, 4]))         # 4
print(len((1, 2)))               # 2
print(len({"a": 1, "b": 2}))     # 2 (counts key-value pairs)
print(len({1, 2, 3}))            # 3

Using len() in Conditions

A common pattern for checking whether a collection is empty or meets a size requirement.

cart = []

if len(cart) == 0:
    print("Your cart is empty")

password = "abc123"
if len(password) < 8:
    print("Password must be at least 8 characters")

Combining len() with range()

Iterating by index when both the position and value are needed (though enumerate() is often cleaner).

fruits = ["apple", "banana", "cherry"]

for i in range(len(fruits)):
    print(f"{i}: {fruits[i]}")

# Often cleaner with enumerate()
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

Best practices

  • Prefer 'if not cart:' over 'if len(cart) == 0:' for checking emptiness - it's more idiomatic and works for any falsy check
  • Use enumerate() instead of range(len(...)) when you need both index and value while looping
  • len() works on any object that implements __len__, including custom classes you define yourself
  • len() raises a TypeError on objects that don't have a defined length, like integers or None

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading