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})) # 3Using 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