How to Find the Length of a List in Python

Learn how to find the length of a list in Python using the len() function. Understand the O(1) time complexity and checking counts.

Try Code in Editor

Explanation

Knowing the number of elements in a collection is crucial when validating user input, dividing data into smaller chunks, paging API queries, or writing loop iterations. In Python, you can find the size or length of any collection using the simple, built-in `len()` function.

Under the hood, Python's list structure is implemented as a variable-length array. It contains an internal counter that tracks the number of elements it holds. When you call `len(my_list)`, Python doesn't traverse the list to count the elements; it simply reads this internal counter. This means the time complexity of `len()` is always O(1) (constant time), making it exceptionally fast regardless of the size of the list.

The `len()` function is generic and works on any iterable object that implements the `__len__` magic method. This means you can use the exact same syntax to find the length of tuples, strings, dictionaries, sets, and custom class instances, maintaining clean consistency throughout your codebase.

Step-by-Step Implementation

  1. 1

    Call the len() function and pass the list variable as its single argument.

  2. 2

    Store the returned integer in a variable or print/evaluate it directly.

  3. 3

    Use the result in conditions or math calculations (like indexing).

Code Example

This script demonstrates finding lengths of lists, strings, and dictionaries using the len() function.

list_length.py
Try in Editor
empty = []
numbers = [10, 20, 30, 40, 50]
words = ["python", "code", "run"]

# 1. Finding lengths of lists
print("Empty list length:", len(empty))
print("Numbers list length:", len(numbers))

# 2. Finding length of a string
text = "Hello, World!"
print("String length:", len(text))

# 3. Finding length of a dictionary
details = {"id": 1, "name": "Alice"}
print("Dictionary length:", len(details))
Terminal Output
Empty list length: 0
Numbers list length: 5
String length: 13
Dictionary length: 2

Frequently Asked Questions

Why is len() so fast in Python?

Because Python's built-in collections store their item count internally. Calling len() simply reads a struct field without executing any iteration.

What happens if I call len() on a custom class object?

It will raise a TypeError unless you define the __len__(self) magic method within your custom class definition.

Related How-To Guides

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.