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
At a glance
- Purpose
- Scripting and general-purpose applications
- File extension
- .py
- Runs in
- Python interpreter
- Usually used with
- Python standard library and packages
Specifications & further reading
Related Python documentation
Lists
A list is Python's built-in ordered, mutable collection type, created with square brackets. Lists can hold items of any type - even a mix of types - and support indexing, slicing, and a wide range of built-in methods for adding, removing, and reordering elements. Because they are mutable, lists can be changed in place after creation, which makes them the go-to structure for collections that grow or shrink over time.Tuples
A tuple is an ordered, immutable collection, created with parentheses (or often just commas). Once created, a tuple's contents cannot be changed, added to, or removed - this immutability makes tuples faster than lists and safe to use as dictionary keys or in sets. Tuples are commonly used for fixed collections of related values, like coordinates or RGB colors, and for returning multiple values from a function.Dictionaries
A dictionary stores data as key-value pairs, created with curly braces. Keys must be unique and hashable (strings, numbers, or tuples are common choices), while values can be anything, including other dictionaries or lists. Since Python 3.7, dictionaries maintain insertion order. They are one of the most heavily used data structures in Python, ideal for representing structured records, lookups, and mappings.Sets
A set is an unordered collection of unique, hashable items, created with curly braces or the set() function. Sets automatically eliminate duplicates and support fast membership testing, along with mathematical set operations like union, intersection, and difference. They're especially useful for deduplicating data and for comparing two collections to find overlaps or differences.
A list is Python's built-in ordered, mutable collection type, created with square brackets. Lists can hold items of any type - even a mix of types - and support indexing, slicing, and a wide range of built-in methods for adding, removing, and reordering elements. Because they are mutable, lists can be changed in place after creation, which makes them the go-to structure for collections that grow or shrink over time.Tuples
A tuple is an ordered, immutable collection, created with parentheses (or often just commas). Once created, a tuple's contents cannot be changed, added to, or removed - this immutability makes tuples faster than lists and safe to use as dictionary keys or in sets. Tuples are commonly used for fixed collections of related values, like coordinates or RGB colors, and for returning multiple values from a function.Dictionaries
A dictionary stores data as key-value pairs, created with curly braces. Keys must be unique and hashable (strings, numbers, or tuples are common choices), while values can be anything, including other dictionaries or lists. Since Python 3.7, dictionaries maintain insertion order. They are one of the most heavily used data structures in Python, ideal for representing structured records, lookups, and mappings.Sets
A set is an unordered collection of unique, hashable items, created with curly braces or the set() function. Sets automatically eliminate duplicates and support fast membership testing, along with mathematical set operations like union, intersection, and difference. They're especially useful for deduplicating data and for comparing two collections to find overlaps or differences.