Python len() Function: Measuring Object Size

Discover the len() function in Python: how to measure the length of strings, lists, tuples, and other objects. Practical examples and best practices.
9 min read
Believemy logo

The len() function is one of the most commonly used functions in Python. It allows you to measure the size or length of an object, whether it's a string, a list, a tuple, a dict, or any other iterable object. Mastering this function is essential for any Python developer, and you'll find it in virtually every program you write. If you want to deepen your Python knowledge, we recommend taking our comprehensive Python course which covers this function and many other fundamental concepts in detail.

 

Definition of the len() Function

The len() function is a built-in Python function that returns the number of elements contained in an object. The term "len" is an abbreviation of the English word "length".

The syntax of this function is particularly simple:

PYTHON
len(object)

This function accepts a single argument: the object whose size you want to know. It returns an integer representing the number of elements in that object.

Good to know

The len() function works with all types of sequences and collections in Python, making it a versatile and indispensable tool in your developer toolkit.

 

Object Types Compatible with len()

The len() function can be used with many types of objects in Python. Here's a summary table of the main compatible types:

Object TypeWhat len() Returns
str (string)Number of characters
listNumber of elements in the list
tupleNumber of elements in the tuple
dictNumber of key-value pairs
setNumber of unique elements
frozensetNumber of unique elements
rangeNumber of elements in the sequence
bytesNumber of bytes
bytearrayNumber of bytes

 

Practical Examples with len()

Measuring the Length of a String

The most common use of len() is undoubtedly measuring the length of a string. Every character counts, including spaces and special characters.

PYTHON
# Measuring the length of a simple string
message = "Hello Python"
length = len(message)
print(length)  # Output: 12

# Spaces count as characters
phrase = "Hello World"
print(len(phrase))  # Output: 11

# Special and accented characters count too
accented_text = "été"
print(len(accented_text))  # Output: 3

# An empty string has a length of 0
empty_string = ""
print(len(empty_string))  # Output: 0

 

Counting Elements in a List

With lists, the len() function returns the number of elements contained in the list, regardless of their type.

PYTHON
# List of numbers
numbers = [1, 2, 3, 4, 5]
print(len(numbers))  # Output: 5

# Mixed list with different types
mixed = [1, "text", 3.14, True, None]
print(len(mixed))  # Output: 5

# List containing other lists (nested lists)
nested = [[1, 2], [3, 4, 5], [6]]
print(len(nested))  # Output: 3 (number of sublists)

# Empty list
empty_list = []
print(len(empty_list))  # Output: 0
Warning

Warning: for a nested list, len() only counts the first-level elements. To count all elements including those in sublists, you'll need to implement recursive logic.

 

Using len() with Tuples

The behavior of len() with tuples is identical to that with lists.

PYTHON
# Simple tuple
coordinates = (10, 20, 30)
print(len(coordinates))  # Output: 3

# Tuple with a single element
singleton = (42,)
print(len(singleton))  # Output: 1

# Empty tuple
empty_tuple = ()
print(len(empty_tuple))  # Output: 0

 

Counting Dictionary Entries

For dicts, the len() function returns the number of key-value pairs.

PYTHON
# Simple dictionary
user = {
    "last_name": "Smith",
    "first_name": "John",
    "age": 30,
    "city": "Paris"
}
print(len(user))  # Output: 4

# Empty dictionary
empty_dict = {}
print(len(empty_dict))  # Output: 0

# Counting keys or values separately
print(len(user.keys()))    # Output: 4
print(len(user.values()))  # Output: 4

 

Measuring the Size of Sets

sets contain only unique elements. The len() function therefore returns the number of distinct elements.

PYTHON
# Set with unique elements
fruits = {"apple", "banana", "orange", "kiwi"}
print(len(fruits))  # Output: 4

# Duplicates are automatically removed
numbers = {1, 2, 2, 3, 3, 3}
print(len(numbers))  # Output: 3 (only unique values)

# Frozenset works the same way
immutable_set = frozenset([1, 2, 3, 4, 5])
print(len(immutable_set))  # Output: 5

 

Using len() with range

The len() function also works with range objects, which can be very useful for knowing the number of iterations in a loop.

PYTHON
# Simple range
sequence = range(10)
print(len(sequence))  # Output: 10 (from 0 to 9)

# Range with start and end
sequence2 = range(5, 15)
print(len(sequence2))  # Output: 10 (from 5 to 14)

# Range with step
sequence3 = range(0, 20, 2)
print(len(sequence3))  # Output: 10 (0, 2, 4, 6, 8, 10, 12, 14, 16, 18)

 

Advanced Use Cases

Validating User Input Length

The len() function is very useful for validating data entered by users.

PYTHON
def validate_password(password):
    """Checks that the password meets length criteria."""
    if len(password) < 8:
        return "Password must contain at least 8 characters."
    elif len(password) > 128:
        return "Password must not exceed 128 characters."
    else:
        return "Password length is valid."

# Testing the function
print(validate_password("abc"))          # Too short
print(validate_password("myPassword123"))  # Valid

 

Checking if a Collection is Empty

Comparing the length to zero is a common way to check if a collection is empty, although Python offers more idiomatic alternatives.

PYTHON
my_list = []

# Method with len()
if len(my_list) == 0:
    print("The list is empty")

# Pythonic method (recommended)
if not my_list:
    print("The list is empty")

# Check that a list contains elements
if len(my_list) > 0:
    print("The list contains elements")

# Equivalent pythonic method
if my_list:
    print("The list contains elements")
Good to know

In Python, an empty collection evaluates to False in a boolean context, while a non-empty collection evaluates to True. This property allows you to write more concise and idiomatic code.

 

Iterating Over a Sequence with Its Index

The len() function is often used in combination with range() to iterate over a sequence while having access to indices.

PYTHON
names = ["Alice", "Bob", "Charlie", "Diana"]

# Iteration with len() and range()
for i in range(len(names)):
    print(f"Index {i}: {names[i]}")

# Result:
# Index 0: Alice
# Index 1: Bob
# Index 2: Charlie
# Index 3: Diana

# More pythonic alternative with enumerate()
for i, name in enumerate(names):
    print(f"Index {i}: {name}")

 

Implementing len() in Your Own Classes

You can make your own classes compatible with the len() function by implementing the special __len__ method.

PYTHON
class ShoppingCart:
    """Class representing a shopping cart."""
    
    def __init__(self):
        self.items = []
    
    def add(self, item):
        """Adds an item to the cart."""
        self.items.append(item)
    
    def __len__(self):
        """Returns the number of items in the cart."""
        return len(self.items)

# Usage
cart = ShoppingCart()
print(len(cart))  # Output: 0

cart.add("Apples")
cart.add("Bread")
cart.add("Milk")
print(len(cart))  # Output: 3

 

Best Practices with len()

Avoid Repeated Calls to len()

If you need to use an object's length multiple times, store it in a variable to avoid repeated calls.

PYTHON
# Bad practice: multiple calls to len()
for i in range(len(my_list)):
    if i < len(my_list) - 1:  # Unnecessary call
        print(my_list[i])

# Good practice: store the length
length = len(my_list)
for i in range(length):
    if i < length - 1:
        print(my_list[i])

 

Prefer Pythonic Methods

Python often offers more elegant alternatives than using len() directly.

PYTHON
# Instead of:
if len(liste) == 0:
    pass

# Prefer:
if not liste:
    pass

# Instead of:
for i in range(len(liste)):
    element = liste[i]

# Prefer:
for element in liste:
    pass

# Or if you need the index:
for i, element in enumerate(liste):
    pass

 

Handling TypeError Exceptions

The len() function raises a TypeError exception if you call it on an object that doesn't support the notion of length.

PYTHON
# Types that don't support len()
try:
    print(len(42))  # int
except TypeError as e:
    print(f"Error: {e}")

try:
    print(len(3.14))  # float
except TypeError as e:
    print(f"Error: {e}")

try:
    print(len(None))  # NoneType
except TypeError as e:
    print(f"Error: {e}")

# Check if an object supports len()
def supports_len(obj):
    """Checks if an object supports the len() function."""
    try:
        len(obj)
        return True
    except TypeError:
        return False

print(supports_len([1, 2, 3]))  # True
print(supports_len(42))         # False

 

Algorithmic Complexity of len()

The len() function has a time complexity of O(1) (constant time) for Python's native types. This means that the execution time doesn't depend on the size of the object.

This efficiency is possible because Python stores the length of objects as an internal attribute, rather than calculating it on each call.

PYTHON
import time

# Length is calculated in constant time
small_list = list(range(10))
large_list = list(range(10_000_000))

# Both operations take roughly the same time
start = time.time()
len(small_list)
print(f"Small list: {time.time() - start:.10f} seconds")

start = time.time()
len(large_list)
print(f"Large list: {time.time() - start:.10f} seconds")

 

Frequently Asked Questions

Question

What's the difference between len() and the count() method?

The len() function returns the total number of elements in a sequence, while the count() method returns the number of occurrences of a specific element. For example, len([1, 2, 2, 3]) returns 4, whereas [1, 2, 2, 3].count(2) returns 2 (because the number 2 appears twice).

 

Question

Can you use len() on a generator or an iterator?

No, the len() function doesn't work directly with generators and iterators, because their length isn't known in advance. To count the elements of a generator, you must either convert it to a list with len(list(generator)), or use a loop with a counter. Be careful though, converting a generator to a list consumes it entirely and uses memory.

 

Question

How do you count elements in a nested list?

To count all elements in a nested list (including those in sublists), you need to use a recursive function:

PYTHON
def count_elements(lst):
    total = 0
    for element in lst:
        if isinstance(element, list):
            total += count_elements(element)
        else:
            total += 1
    return total

nested_list = [[1, 2], [3, [4, 5]], 6]
print(count_elements(nested_list))  # Output: 6

 

Question

How can I learn to master Python and its built-in functions?

To master Python and all its built-in functions like len(), it's essential to practice regularly and follow a structured course. We recommend our Python course on Believemy which will guide you step by step in learning the language, from basics to advanced concepts, with many practical exercises to consolidate your knowledge.

Related terms

Discover our python glossary

Browse the terms and definitions most commonly used in development with Python.

Share this article

Want to help us? Share this article on your networks or even better: on your site, in an article or in your newsletter.