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.


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.


Syntax of Python len

The function follows this simple structure:

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.

Example:

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:

colors = ["red", "green", "blue"]
print(len(colors))  # Output: 3

This shows how list len in Python returns the total count of list elements.


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:

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.


Using len with Tuples and Sets

You can apply len() to other collections as well:

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.


Using len with Dictionaries

When used with dictionaries, len() returns the number of key-value pairs.

Example:

person = {"name": "Alice", "age": 30, "city": "Paris"}
print(len(person))  # Output: 3

This shows the length of the dictionary 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:

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.

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.


Using len with Ranges

You can use len() to get the number of values in a range object:

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.

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.


Validating Input with len

You can use len() to validate inputs such as passwords or usernames:

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.


Combining len with Conditionals

Using len() inside conditionals allows decisions based on content size.

shopping_cart = []
if len(shopping_cart) == 0:
    print("Cart is empty.")

This approach helps simplify logic when checking for content presence.


Custom Classes and len

You can enable your own objects to work with len() by defining a __len__() method.

Example:

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.


Edge Cases with len

  • Empty strings return 0:

    len("")  # Output: 0
    
  • Nested lists return only the top-level count:

    len([[1, 2], [3, 4]])  # Output: 2
    
  • Objects without __len__ will raise TypeError:

    len(42)  # TypeError
    

Knowing these edge cases will help avoid runtime surprises.


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.


Best Practices for Using len in Python

  1. Avoid redundant calls: Save the result of len() if you need it multiple times.

    n = len(my_list)
    for i in range(n):
        # Do something
    
  2. Use direct truthiness when possible:

    if my_list:
        # Better than len(my_list) > 0
    
  3. Don’t use len() on iterators: Generators and iterators don’t support length.

    gen = (i for i in range(10))
    len(gen)  # TypeError
    

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.

Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH

Reach your coding goals faster