len()

The built-in len() function returns the number of items in an object, such as sequences or collections. It’s useful for determining the size of data structures:

Python
>>> len([1, 2, 3, 4])
4

len() Signature

Python Syntax
len(obj, /)

Arguments

Argument Description
obj An object that supports the length

Return Value

  • Returns an integer representing the number of items in the input object.

len() Examples

With a string as an argument:

Python
>>> len("Hello")
5

With lists and tuples as an argument:

Python
>>> len([1, 2, 3, 4])
4
>>> len(("John", "Python Dev", "Canada"))
3

With dictionaries and sets as an argument:

Python
>>> len({"name": "Jane", "age": 25})
2
>>> len({"red", "green", "blue"})
3

len() Common Use Cases

The most common use cases for the len() function include:

  • Determining the number of elements in a list, tuple, or set.
  • Counting the number of characters in a string.
  • Calculating the number of key-value pairs in a dictionary.
  • Explicitly checking whether a container is empty by comparing len() to 0.

len() Real-World Example

You can use len() to validate user input, such as ensuring a username is within a certain length:

Python username.py
username = input("Enter a username: ")

if 4 <= len(username) <= 12:
    print("Username is valid.")
else:
    print("Username must be between 4 and 12 characters.")

In this example, you use len() to check whether the entered username meets the required length criteria, ensuring valid input.

len() in Custom Classes

You can support len() in your custom classes by implementing the .__len__() special method. Here’s an example:

Python box.py
class Box:
    def __init__(self, items):
        self.items = items

    def __len__(self):
        return len(self.items)

# Usage
box = Box([1, 2, 3, 4, 5])
print(len(box))  # Output: 5

By implementing .__len__(), you enable your custom class to work seamlessly with the len() function, providing a way to determine the number of items it contains.

Tutorial

Using the len() Function in Python

In this tutorial, you'll learn how and when to use the len() Python function. You'll also learn how to customize your class definitions so that objects of a user-defined class can be used as arguments in len().

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 22, 2024 • Reviewed by Dan Bader