PYTHON
Python len() Function: Syntax, Usage, and Practical Examples
The Python len() function is a built-in utility used to determine the number of items in an object. It provides a consistent and efficient way to measure the length of sequences, collections, and other iterable data types. Mastering how len() behaves across different contexts is essential for writing clean, concise, and readable code.
Along with other built-in functions, len() shows up constantly in Python code.
Learn Python on Mimo
What Is Python len?
The Python len() function returns the number of elements in an object such as a list, string, tuple, dictionary, or any collection that implements a length property. It is often one of the first functions that new Python developers learn and is foundational to many programming patterns.
Using len() avoids the need to manually count elements, making it indispensable for loops, conditionals, and validations.
In this quick tutorial, you’ll see how len() works in a few common situations you’ll run into while coding.
Syntax of Python len
The function follows this simple structure:
Python
len(object)
object: The object whose length is to be determined. This must be a type that supports length calculation, such as a list, string, dictionary, set, or tuple.
The return value is an integer that represents the number of items.
Example:
Python
fruits = ["apple", "banana", "cherry"]
print(len(fruits)) # Output: 3
Here, the Python len() function returns the number of elements in the list.
Using len with Lists
One of the most common uses of len() is to count items in a list.
Example:
Python
colors = ["red", "green", "blue"]
print(len(colors)) # Output: 3
This shows how list len in Python returns the total count of list elements. A Python list can hold mixed types, and it can change over time because lists are mutable.
Using len with Strings
The len() function can also be used to determine the number of characters in a string, including spaces and punctuation.
Example:
Python
message = "Hello, world!"
print(len(message)) # Output: 13
If you're wondering about the Python len of a string, this is the most direct way to obtain it. If you need the length of a string before trimming it, slicing it, or checking a minimum size, len() is the simplest option.
Using len with Tuples and Sets
You can apply len() to other collections as well:
Python
my_tuple = (1, 2, 3, 4)
print(len(my_tuple)) # Output: 4
my_set = {"apple", "banana", "cherry"}
print(len(my_set)) # Output: 3
These examples demonstrate how the function behaves consistently across different data structures.
You can also measure a frozen set (created with frozenset()), which behaves like a set that you can’t modify after it’s created.
Using len with Dictionaries
When used with dictionaries, len() returns the number of key-value pairs.
Example:
Python
person = {"name": "Alice", "age": 30, "city": "Paris"}
print(len(person)) # Output: 3
This shows the length of the dictionary (dict) Python uses to determine how many entries it holds.
Using len with Arrays
Python’s built-in arrays (via the array module) or lists can both be measured using len().
Example:
Python
import array
nums = array.array("i", [1, 2, 3, 4, 5])
print(len(nums)) # Output: 5
For more complex array operations (like in NumPy), len() still returns the first dimension.
Python
import numpy as np
matrix = np.array([[1, 2], [3, 4], [5, 6]])
print(len(matrix)) # Output: 3
This provides the array length in Python, giving insight into the outermost structure.
If you work with dataframes, len() is also handy in Pandas:
Python
import pandasas pd
df = pd.DataFrame({"name": ["Ava","Sam"],"score": [88,91]})
print(len(df))# Output: 2
Using len with Ranges
You can use len() to get the number of values in a range object:
Python
r = range(1, 10, 2)
print(len(r)) # Output: 5
len() calculates how many steps are taken in the defined range.
Python len in Loops
The len() function is often used to create loop conditions.
Python
names = ["Alice", "Bob", "Charlie"]
for i in range(len(names)):
print(names[i])
However, in modern Python, enumerate() or direct iteration is preferred. Still, knowing how to use len of a list in Python within loops is useful for legacy code.
You’ll also see len() used in a while loop when you need manual control over an index:
Python
names = ["Asha","Diego","Mina"]
i =0
while i <len(names):
print(names[i])
i +=1
And sometimes, you can avoid indexing entirely by building results directly with a list comprehension.
Validating Input with len
You can use len() to validate inputs such as passwords or usernames:
Python
password = input("Enter password: ")
if len(password) < 8:
print("Password too short!")
else:
print("Password accepted.")
This use case demonstrates what len does in Python in a practical authentication scenario.
This user input check is a simple, real-world validation step.
Combining len with Conditionals
Using len() inside conditionals allows decisions based on content size.
Python
shopping_cart = []
if len(shopping_cart) == 0:
print("Cart is empty.")
This approach helps simplify logic when checking for content presence.
The comparison (len(shopping_cart) == 0) evaluates to a boolean.
Custom Classes and len
You can enable your own objects to work with len() by defining a __len__() method.
Example:
Python
class Box:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
b = Box([1, 2, 3])
print(len(b)) # Output: 3
This highlights how to customize Python len() behavior in your classes, which is a common pattern in OOP.
Edge Cases with len
- Empty strings return 0:
Python
len("") # Output: 0 - Nested lists return only the top-level count:
Python
len([[1, 2], [3, 4]]) # Output: 2 - Objects without
__len__will raiseTypeError:Python
len(42) # TypeError
If you’re doing a quick list length check, remember that len() only tells you how many items you have, not what’s inside them.
Knowing these edge cases will help avoid runtime surprises.
Troubleshooting TypeError and Tracebacks
If len() fails, Python usually tells you exactly what happened in the traceback. For example, calling len() on a number raises TypeError because integers don’t have a length. When you read the error, look for the line where len(...) is called and check what type you passed in.
Performance of len
The len() function runs in constant time—O(1)—because most Python data structures store their length as an internal attribute. This means calling len() does not require scanning the entire structure.
This performance aspect makes len Python efficient and safe to use in loops and conditionals, especially inside algorithms that would get slow if they had to recount items repeatedly.
Best Practices for Using len in Python
-
Avoid redundant calls: Save the result of
len()if you need it multiple times.Python
n = len(my_list) for i in range(n): # Do something -
Use direct truthiness when possible:
Python
if my_list: # Better than len(my_list) > 0 -
Don’t use
len()on iterators: Generators and iterators don’t support length.Python
gen = (i for i in range(10)) len(gen) # TypeError
If you post examples to Github, include the input data in the snippet so others can reproduce the same output.
Summary
The Python len() function is a core part of the language, giving you instant access to the size of data structures like lists, strings, dictionaries, arrays, and more. You’ve seen how len() Python offers is consistent, efficient, and customizable, making it an essential utility in your coding toolkit.
You learned how to use len() of a list in Python, len() of dictionary Python objects, len() of arrays, and how to implement __len__() in custom classes.
Whether you are validating input, managing loops, or working with custom objects, mastering Python len() is a small step with a big impact on code quality.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot