Report this

What is the reason for this report?

How to find the length of a list in Python

Updated on July 25, 2025
Safa MulaniAndrea AndersonManikandan Kurup

By Safa Mulani, Andrea Anderson and Manikandan Kurup

How to find the length of a list in Python

Introduction

In Python programming, one of the most fundamental operations is determining the size or length of a collection. For lists, which are one of the most versatile and commonly used data structures, knowing the number of elements they contain is essential for a wide range of tasks, from iterating with loops to implementing complex algorithms. Whether you need to validate input, control program flow, or allocate resources, getting the length of a list is a task you may perform frequently.

This article provides a comprehensive and detailed guide on how to find the length of a list in Python. We will begin with the standard, most efficient method recommended for all use cases. We will then explore several alternative methods, not as practical replacements, but as educational tools to deepen your understanding of Python’s core mechanics, including loops and functional programming constructs. We will also cover more advanced topics such as nested lists, performance implications, and common errors to ensure you have a complete mastery of this concept.

Key Takeaways

  • The built-in len() function is the single best and most efficient method to find the length of a list in Python.
  • len() has a constant time complexity of O(1), making it instantly fast, while all alternative methods are significantly slower with a linear complexity of O(n).
  • For checking if a list is empty, the Pythonic approach is to use its implicit boolean value (if not my_list:) rather than explicitly checking its length.
  • On nested lists, len() only counts the top-level elements; you need a custom recursive function to count every item within the inner lists.
  • The len() function is universal and works on any Python object that implements the __len__() method, including strings, dictionaries, and custom classes.
  • A TypeError arises from using len() on objects without a length like numbers, while an IndexError occurs when confusing length with the maximum index, which is always len(list) - 1.
  • Alternative methods like loops or reduce() are useful for understanding Python’s internals but should never be used in practice to get a list’s length due to poor performance.
  • To iterate over a list, it’s better to loop directly (for item in my_list:) or use enumerate() instead of the less-Pythonic for i in range(len(my_list)): pattern.

The most direct, efficient, and “Pythonic” way to get the number of items in a list is by using Python’s built-in len() function. This function is a core part of the language and is designed to be highly optimized for this exact purpose.

The len() function is universal and can be used to get the length of any object that has a defined length, including other sequence types (like strings, tuples, and ranges) and collection types (like dictionaries and sets).

The syntax is straightforward: you pass the list as the sole argument to the function.

len(your_list)

When you call len() on an object, Python does not iterate through the elements to count them one by one. Instead, it calls the object’s special __len__() dunder (double underscore) method. For built-in objects like lists, this method is implemented in C and is extremely fast because lists in Python maintain a counter for their size. Accessing this counter is an instantaneous operation, regardless of the list’s size.

This means that len() has a constant time complexity, denoted as O(1). It takes the same amount of time to get the length of a list with 10 million elements as it does for a list with 10 elements.

Let’s look at a practical example. Suppose we have a list of programming languages.

languages = ['Python', 'Java', 'C++', 'JavaScript', 'Go']

list_length = len(languages)

print(f"The list contains {list_length} elements.")

Output:

The list contains 5 elements.

In this example, when we call len(languages), Python internally accesses the size property of the languages list object and immediately returns the value 5, which is then stored in the list_length variable. Because of its simplicity, readability, and unparalleled performance, len() should always be your default choice for finding the length of a list.

Alternative methods

While len() is the definitive solution, exploring other methods can be a valuable exercise to better understand Python’s iteration protocols and functional tools. The following methods are presented for educational purposes and are not recommended for production code where performance and clarity are priorities.

How to Use a for Loop

A for loop is the most fundamental way to iterate over the elements of a list. We can use this structure to manually count the elements. This approach involves initializing a counter variable to zero and then incrementing it for each item in the list.

The for loop requests an iterator from the list and repeatedly calls it to get the next item until a StopIteration exception is raised (which the for loop handles internally). For each successful retrieval of an item, we increment our counter.

Let’s see a code example:

numbers = [10, 20, 30, 40, 50, 60]

count = 0

for element in numbers:
    count = count + 1

print(f"The length of the list calculated with a for loop is: {count}")

Output:

The length of the list calculated with a for loop is: 6

In this code, count starts at 0. The loop runs once for each element in the numbers list. During each iteration, count = count + 1 is executed. After the loop completes, count holds the total number of elements. This method is less efficient than len(), due to its linear time complexity of O(n), meaning the execution time grows directly with the number of elements in the list.

How to Use a while Loop with try/except

Another, more obscure way to count elements involves using a while loop combined with exception handling. This method is highly unconventional and generally discouraged due to its side effects and poor readability, but it serves as an interesting example of controlling program flow with try...except.

This approach uses a while True loop that continuously attempts to remove an element from the list using the list.pop() method. Each time pop() successfully removes an element, a counter is incremented. When the list becomes empty, pop() raises an IndexError, which we catch with an except block to break the loop.

Important Note: This method is destructive; it will modify and empty the original list.

Let’s see an example:

data_list = ['apple', 3.14, True, None]

data_list_copy = data_list.copy()

count = 0
while True:
    try:
        data_list_copy.pop()
        count += 1
    except IndexError:
        break

print(f"The original list was: {data_list}")
print(f"The length calculated with a while loop is: {count}")
print(f"The list after the loop is: {data_list_copy}")

Output:

The original list was: ['apple', 3.14, True, None]
The length calculated with a while loop is: 4
The list after the loop is: []

As you can see, the copied list is empty after the loop finishes. This demonstrates the destructive nature of this technique. Its complexity is also O(n).

How to Use List Comprehension with sum()

This is a clever one-liner that combines list comprehension with the built-in sum() function. It’s more concise than a manual loop but less efficient and readable than len().

The core of this method is the expression [1 for _ in your_list]. This list comprehension iterates through the entire list and generates a new list containing the number 1 for each element in the original list. The underscore _ is used as a conventional placeholder for a variable that we don’t need to use. Finally, the sum() function is called on this new list of ones, effectively summing them up to get the total count.

Here’s an example:

letters = ['a', 'b', 'c', 'd']

list_length = sum([1 for _ in letters])

print(f"The length calculated with list comprehension is: {list_length}")

Output:

The length calculated with list comprehension is: 4

This method is functionally correct but involves creating an entirely new list in memory just to hold temporary 1s. This makes it inefficient in terms of both memory and speed (O(n) complexity) compared to len(). A slightly more memory-efficient variant uses a generator expression: sum(1 for _ in letters).

How to Use enumerate()

The enumerate() function is a handy tool when you need both the index and the value of each element during iteration. While its primary purpose isn’t to find the length, you can use it to achieve that goal.

enumerate() takes an iterable (like a list) and returns an enumerate object, which yields pairs of (index, value) during iteration. To find the length, we can simply loop through the entire list and grab the index of the last element. The length will be that last index plus one.

Here’s an example:

my_list = [2, 4, 6, 8, 10, 12, 14, 16]
length = 0

if my_list:  
    for i, _ in enumerate(my_list):
        pass
    length = i + 1

print(f"The length calculated with enumerate() is: {length}")

Output:

The length calculated with enumerate() is: 8

This method is clearly inefficient (O(n)) and verbose for simply finding the length. It requires iterating through the entire list just to find the final index. It is only practical if you are already iterating through the list with enumerate() for another reason and want to capture the length as part of that process.

How to Use functools.reduce()

For those interested in functional programming paradigms, Python’s functools.reduce() offers another way to solve this problem. reduce applies a function of two arguments cumulatively to the items of a sequence, so as to reduce the sequence to a single value.

To find the length, we can use a reducer function (often a lambda) that takes an accumulated count and the current item as arguments. For each item, it simply returns the accumulated count plus one. We need to provide an initial value for the accumulator, which will be 0.

Let’s see an example:

from functools import reduce

values = [100, 200, 300]

list_length = reduce(lambda count, _: count + 1, values, 0)

print(f"The length calculated with reduce() is: {list_length}")

Output:

The length calculated with reduce() is: 3

This method is powerful for cumulative operations like summing or finding a product, but for counting elements, it’s overly complex and less performant (O(n)) than len(). It is primarily a tool for demonstrating functional programming concepts in Python.

How to Find the Length of Nested Lists

A common point of confusion arises when dealing with nested lists (lists that contain other lists). When you use len() on a nested list, it only counts the elements at the top level.

How to Use len() on a Nested List

nested_list = [[1, 2], [3, 4], 5, [6, 7, 8]]

top_level_length = len(nested_list)

print(f"The nested list is: {nested_list}")
print(f"The top-level length is: {top_level_length}")

Output:

The nested list is: [[1, 2], [3, 4], 5, [6, 7, 8]]
The top-level length is: 4

If you need to find the total number of all individual (non-list) items across all levels, you must iterate through the list recursively.

How to Find the Total Elements in a Nested List

Here is a function that recursively traverses a list to count all atomic elements.

def count_total_elements(data):
    """
    Recursively counts the total number of non-list elements in a list.
    """
    count = 0
    for element in data:
        if isinstance(element, list):
            count += count_total_elements(element)
        else:
            count += 1
    return count

deep_list = [1, [2, 3], [4, [5, 6]], 7]

total_count = count_total_elements(deep_list)

print(f"The deeply nested list is: {deep_list}")
print(f"The total number of all elements is: {total_count}")

Output:

The deeply nested list is: [1, [2, 3], [4, [5, 6]], 7]
The total number of all elements is: 7

This recursive function checks each element. If the element is itself a list, the function calls itself on that sub-list, adding the result to the running total. Otherwise, it increments the count by one.

How to Handle Edge Cases

A hallmark of a well-designed function is its ability to handle edge cases gracefully and predictably. The len() function is exceptionally robust in this regard. Understanding how it behaves in non-standard situations is key to preventing bugs and leveraging it effectively in your algorithms. Let’s explore these scenarios in greater detail.

1. The Empty List

The most fundamental edge case is an empty list ([]). This is a common state for a list, for example, before it’s populated with data or after all its elements have been processed. The len() function handles this perfectly.

Calling len() on an empty list correctly and efficiently returns 0.

empty_list = []
length = len(empty_list)

print(f"The list is: {empty_list}")
print(f"The length of an empty list is: {length}")

Output:

The list is: []
The length of an empty list is: 0

This predictable behavior is crucial for control flow. The Pythonic way to check for an empty list (if not my_list:) relies on the principle that sequences with a length of 0 evaluate to False in a boolean context.

2. Lists Containing None, True, or False

Lists in Python can hold any object. This includes the singleton object None and the boolean values True and False. These are not special cases to len(); they are counted just like any other element.

Each instance of None, True, or False contributes to the list’s total length.

special_values_list = [1, None, True, 3, False, None]
length = len(special_values_list)

print(f"The list is: {special_values_list}")
print(f"The length of the list is: {length}")

Output:

The list is: [1, None, True, 3, False, None]
The length of the list is: 6

This shows that len() is concerned with the quantity of elements, not their value or type. It simply counts the number of object references the list is holding.

3. Lists with Duplicate Elements

Beginners sometimes confuse the behavior of a list’s length with that of a set. A set only stores unique elements, but a list preserves all elements, including duplicates.

len() counts every element in a list, including any and all duplicates.

duplicates_list = ['apple', 'orange', 'apple', 'banana', 'apple']
length = len(duplicates_list)

print(f"The list is: {duplicates_list}")
print(f"The total length (including duplicates) is: {length}")

unique_length = len(set(duplicates_list))
print(f"The number of unique elements is: {unique_length}")

Output:

The list is: ['apple', 'orange', 'apple', 'banana', 'apple']
The total length (including duplicates) is: 5
The number of unique elements is: 3

This distinction is fundamental. Use len(my_list) for the total count and len(set(my_list)) when you need to know the number of unique items.

4. Extremely Large Lists

In fields like data science and machine learning, it’s common to work with lists containing millions or even billions of elements.

The performance of len() remains constant (O(1)) regardless of the list’s size. The primary limitation is not the len() function itself, but the system’s memory (RAM) required to create and hold the list in the first place.

try:
    large_list = list(range(50_000_000))
    print("Successfully created a large list.")
    
    length = len(large_list)
    print(f"Length of the large list is: {length}")
    
except MemoryError:
    print("Failed to create the list due to a MemoryError.")

Output (on a system with sufficient memory):

Successfully created a large list.
Length of the large list is: 50000000

You can be confident that calling len() on a massive list will not be a performance bottleneck in your application. Any performance issues will stem from the creation and manipulation of the list, not from checking its size.

5. Self-Referential Lists

A true edge case is a list that contains a reference to itself. This creates a recursive, or circular, data structure.

len() handles this without issue and does not enter an infinite loop. It counts the reference to the list itself as a single element.

recursive_list = [1, 'hello', 3]

recursive_list.append(recursive_list)

print(f"The recursive list prints as: {recursive_list}")

length = len(recursive_list)
print(f"The length of the recursive list is: {length}")

Output:

The recursive list prints as: [1, 'hello', 3, [...]]
The length of the recursive list is: 4

This demonstrates that len() operates at a shallow level. It counts the number of “slots” or pointers at the top level of the list’s data structure. It does not traverse the elements or follow the references. The fourth slot in our recursive_list contains a pointer back to the list object itself, and len() simply counts that pointer, giving a total of 4.

Performance Considerations

When you choose a method to accomplish a task in programming, performance is often a key factor. For an operation as common as finding a list’s length, the performance difference between the standard approach and the alternatives is not just a minor detail; it’s a fundamental distinction that can significantly impact your application’s speed, especially when working with large datasets.

Understanding Time Complexity

Time complexity is a concept used to describe how the runtime of an algorithm scales with the size of its input (denoted as ‘n’).

len(): The Power of O(1) Constant Time

The len() function has a time complexity of O(1), which means its execution time is constant. It takes the same amount of time to complete regardless of the size of the list.

This is possible because Python’s list objects are implemented in C as a structure (PyListObject). This structure doesn’t just contain a pointer to the elements; it also contains a dedicated field, ob_size, that stores the number of items in the list. This field is automatically updated whenever an item is added or removed. When you call len(my_list), Python simply returns the value of this ob_size field. It’s a direct memory access, not a computation that involves the elements.

Alternative Methods: The Cost of O(n) Linear Time

All the other methods we discussed, using a for loop, a while loop, sum(), enumerate(), or reduce, have a time complexity of O(n). This means their execution time scales linearly with the number of elements in the list.

These methods must visit, or iterate over, every single element in the list to determine the total count.

  • A for loop explicitly steps through each item to increment a counter.
  • sum(1 for _ in my_list) iterates through the whole list to generate a sequence of 1s, which are then summed.
  • If a list has 10 elements, the loop runs 10 times. If it has 10 million elements, the loop must run 10 million times. The work to be done is directly proportional to the size of the list.

The table below summarizes this critical difference:

Method Time Complexity How It Works
len(my_list) O(1) (Constant) Reads a pre-calculated size from the list object’s metadata.
for loop counter O(n) (Linear) Iterates through every element one by one to increment a counter.
while loop with try/except O(n) (Linear) Repeatedly removes elements and counts them until the list is empty.
sum(1 for _ in my_list) O(n) (Linear) Iterates through every element to build and sum a new sequence.
enumerate() O(n) (Linear) Iterates through the entire list to find the index of the last element.
functools.reduce() O(n) (Linear) Applies a function cumulatively by visiting each element in sequence.

A Practical Benchmark

Theoretical knowledge is great, but seeing the difference in practice is even better. We can use Python’s built-in timeit module to measure the execution speed of these methods on both a small and a very large list.

import timeit
from functools import reduce

small_list = list(range(100))
large_list = list(range(10000000))

def len_method(mylist):
  return len(mylist)

def for_loop_method(mylist):
  count = 0
  for element in mylist:
    count = count + 1
  return count

def while_method(mylist):
  list_copy = mylist.copy()
  count = 0
  while True:
    try:
      list_copy.pop()
      count += 1
    except IndexError:
      break
  return count

def list_sum_method(mylist):
  list_len = sum([1 for _ in mylist])
  return list_len

def enumerate_method(mylist):
  length = 0
  if mylist:
    for i, _ in enumerate(mylist):
      pass
    length = i+1
  return length

def reduce_method(mylist):
  length = reduce(lambda count, _: count+1, mylist, 0)
  return length

methods = [len_method, for_loop_method, while_method, list_sum_method, enumerate_method, reduce_method]

# Simple benchmarking
print("Testing with small list (100 elements):")
for method in methods:
    time_taken = timeit.timeit(lambda: method(small_list), number=1000)
    print(f"{method.__name__}: {time_taken:.6f} seconds")

print("\nTesting with large list (10M elements):")
for method in methods:
    time_taken = timeit.timeit(lambda: method(large_list), number=10)
    print(f"{method.__name__}: {time_taken:.6f} seconds")

Sample Output:

Testing with small list (100 elements):
len_method: 0.000098 seconds
for_loop_method: 0.002202 seconds
while_method: 0.006314 seconds
list_sum_method: 0.003514 seconds
enumerate_method: 0.002377 seconds
reduce_method: 0.005996 seconds

Testing with large list (10M elements):
len_method: 0.000004 seconds
for_loop_method: 4.298573 seconds
while_method: 5.542252 seconds
list_sum_method: 2.760641 seconds
enumerate_method: 4.799447 seconds
reduce_method: 6.974511 seconds

Note: Your exact times will vary based on your computer’s hardware.

As we can see, the built-in len() function is by far the fastest and most efficient way to get the length of a list in Python, thanks to its constant-time complexity (O(1)) that simply reads a stored value. All other methods are significantly slower because they require iterating through every element, resulting in linear time complexity (O(n)), making them significantly slower and impractical for real-world use, especially with large lists.

This isn’t a minor optimization; it’s a critical design choice. In any professional context, len() is the only acceptable method, offering predictable, instantaneous performance essential for scalable applications. While alternative approaches can be valuable for learning about Python’s iteration and functional constructs, they are computationally expensive, and should be avoided in practice.

Comparing with Other Data Types

The true power and elegance of the len() function lie in its universal application across Python’s data model. This is not a coincidence; it’s a deliberate design feature known as “duck typing.” The principle is: “If it walks like a duck and it quacks like a duck, then it must be a duck.”

In Python, this means len() doesn’t care if an object is a list, a str, or a custom object you created. It only cares if the object “quacks” by implementing the special dunder method, __len__(). Any object that has this method can be passed to len() to get its size. Let’s see how this works with various built-in types.

Strings (str)

For a string, len() returns the total number of characters. This is a crucial distinction: it counts characters, not the bytes used to store them, which is important when working with international text (Unicode).

my_string = "Python"
unicode_string = "résumé"

print(f"Length of '{my_string}' is {len(my_string)} characters.")
print(f"Length of '{unicode_string}' is {len(unicode_string)} characters.")

Output:

Length of 'Python' is 6 characters.
Length of 'résumé' is 6 characters.

Tuples (tuple) and Sets (set)

Tuples are ordered, immutable sequences, much like lists. len() behaves identically, counting the total number of elements in the tuple. Sets are unordered collections of unique elements. len() returns the count of these unique elements.

my_tuple = (10, 'hello', True, 10)
my_set = {10, 'hello', True, 10} 

print(f"The tuple {my_tuple} has a length of {len(my_tuple)}.")
print(f"The set {my_set} has a length of {len(my_set)}.")

Output:

The tuple (10, 'hello', True, 10) has a length of 4.
The set {10, True, 'hello'} has a length of 3.

Note: Sets are unordered; your output may appear in a different order.

Dictionaries (dict)

This is a common point of confusion. For a dictionary, len() returns the number of key-value pairs. It does not count the keys and values separately.

my_dict = {
    'name': 'Alice',
    'id': 101,
    'is_active': True
}

print(f"The dictionary has {len(my_dict)} key-value pairs.")

Output:

The dictionary has 3 key-value pairs.

Ranges and Other Efficient Iterables

Some objects, like range, are highly memory-efficient. A range object doesn’t store all the numbers it represents; it only stores its start, stop, and step values. Its length can be calculated mathematically without iteration.

len() on a range object is an O(1) constant-time operation, making it just as fast as calling len() on a list.

large_range = range(1_000_000_000)

print(f"The length of the range is {len(large_range)}.")

Output:

The length of the range is 1000000000.

Your Own Custom Objects

You can make your own classes compatible with len() by implementing the __len__ dunder method. This allows your objects to integrate seamlessly with standard Python functions.

class Team:
    def __init__(self, team_name, members):
        self.name = team_name
        self.members = members

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

dev_team = Team('Frontend Wizards', ['Alice', 'Bob', 'Charlie'])

print(f"The team '{dev_team.name}' has {len(dev_team)} members.")

Output:

The team 'Frontend Wizards' has 3 members.

While len() is straightforward, certain misunderstandings can lead to common errors. Knowing how to anticipate and handle them will make your code more robust.

TypeError: object of type 'X' has no len()

This is the most frequent error. It occurs when you try to call len() on an object that doesn’t have a concept of length, meaning it lacks a __len__ method.

  • Common Causes: Integers (int), floating-point numbers (float), NoneType, and generators.

    # Example of incorrect usage
    count = 5
    # The following line will raise a TypeError because an integer has no length.
    len(count) 
    
  • Defensive Solution: If a variable might hold a list or some other type (like None), check its type before calling len().

    def process_data(data):
        if isinstance(data, list):
            print(f"Data contains {len(data)} items.")
        else:
            print("No data provided.")
    
    process_data([1, 2, 3])
    process_data(None)
    

    Output:

    Data contains 3 items.
    No data provided.
    

IndexError: list index out of range

This error stems from confusing a list’s length with its maximum index.

  • A list of length N has elements indexed from 0 to N−1.

  • Attempting to access the element at index N will fail.

    my_list = ['a', 'b', 'c'] 
    list_len = len(my_list)  
    
    # Trying to access my_list[3] will cause an error.
    try:
        print(my_list[list_len])
    except IndexError as e:
        print(f"Error: {e}")
    
    # The correct way to get the last element:
    last_element = my_list[list_len - 1]
    print(f"The last element is '{last_element}'.")
    

    Output:

    Error: list index out of range
    The last element is 'c'.
    

What are the Best Practices for Writing Clean and Efficient Code?

Following conventions not only improves performance but also makes your code more readable and maintainable for others (and for your future self).

1. Use Implicit Booleans for Emptiness Checks

Instead of explicitly checking if the length is greater than zero, leverage Python’s concept of “truthiness.” All empty collections (lists, tuples, dictionaries, etc.) are considered False in a boolean context, while non-empty ones are True.

empty_list = []
full_list = [1, 2, 3]

# Less Pythonic:
if len(empty_list) > 0:
    pass 

# More Pythonic and readable:
if full_list:
    print("The full_list is not empty.")

Output:

The full_list is not empty.

2. Iterate Directly or Use enumerate()

A common pattern for programmers coming from languages like C or Java is to use range(len()) to loop through a list. While this works, it’s not the Pythonic way.

  • To access elements: Iterate directly over the list.
  • To access both index and element: Use the enumerate() function.
letters = ['x', 'y', 'z']

# Avoid this style:
for i in range(len(letters)):
    print(f"Index: {i}, Value: {letters[i]}")

print("---")

# Prefer this Pythonic style:
for index, value in enumerate(letters):
    print(f"Index: {index}, Value: {value}")

The enumerate approach is cleaner, more readable, and avoids the manual indexing of letters[i].

3. Be Mindful When Finding the Length of Iterators

An iterator (like a generator or a file object) is a “one-time-use” object. Once you loop through it, it’s exhausted. If you need to know the length of its contents, you must first convert it to a list. Be aware that this action will consume the iterator and may use a lot of memory if the iterator yields many items.

my_generator = (x * x for x in range(5))

data_list = list(my_generator)
print(f"The generated data is: {data_list}")
print(f"The length is: {len(data_list)}")

print(f"The generator consumed into a list again is: {list(my_generator)}")

Output:

The generated data is: [0, 1, 4, 9, 16]
The length is: 5
The generator consumed into a list again is: []

If you need to both know the length and iterate over the data multiple times, convert the iterator to a list once and store it in a variable.

Frequently Asked Questions (FAQs)

1. How do I find the length of a list in Python?

To find the number of elements in a Python list, you should use the built-in len() function.

It’s the most direct and efficient way to get the job done. You simply pass the list to the function, and it returns the total count of items.

my_list = ['apple', 'banana', 'cherry']
list_length = len(my_list)

print(list_length) # Output: 3

This method is extremely fast because Python keeps track of the list’s size internally, so len() just retrieves that stored value without counting the elements one by one.

2. Can I use len() on nested lists?

Yes, you can, but it’s important to understand what it counts. The len() function only counts the top-level elements in a list. It treats each inner list as a single item and doesn’t count the items inside it.

# This list has 3 top-level elements: [1, 2], [3, 4], and 5
nested_list = [[1, 2], [3, 4], 5]

print(len(nested_list)) # Output: 3

If you need to count every individual number (for a total of 5 in the example above), you’ll need to write a custom loop that goes into each sub-list and adds up their elements.

3. What if the list is empty?

The len() function handles an empty list perfectly; it correctly returns 0.

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

This behavior is reliable and very useful. In fact, the most Pythonic way to check if a list is empty is to use its “truthiness” directly in a condition, rather than checking its length. An empty list evaluates to False.

my_list = []

if not my_list:
    print("The list is empty!")

4. What’s the difference between len() and list.count()?

They serve two very different purposes.

  • len(my_list) gives you the total number of items in the list.
  • my_list.count(item) tells you how many times a specific item appears in the list.
my_list = ['a', 'b', 'a', 'c', 'a']

print(len(my_list)) # Output: 5

print(my_list.count('a')) # Output: 3

5. Can I make len() work on custom objects?

You can make your objects compatible with len() by implementing the special __len__() dunder method (double underscore) in your class.

When you call len(my_object), Python looks for and calls the my_object.__len__() method behind the scenes. This method should return an integer representing the object’s length.

class Deck:
    def __init__(self):
        self.cards = ['Ace', 'King', 'Queen', 'Jack']

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

my_deck = Deck()
print(len(my_deck)) # Output: 4

Conclusion

Determining the length of a list is a fundamental skill in Python. While the language offers multiple ways to accomplish this, the built-in len() function stands out as the single best solution. It is explicitly designed for this task, offering unparalleled performance (O(1) complexity), clarity, and adherence to Pythonic principles.

While exploring alternatives like manual loops or functional tools like reduce can be a valuable academic exercise in understanding how Python works under the hood, they should not be used in practice for this specific problem. By mastering the use of len(), understanding its behavior with nested lists and edge cases, and following best practices for checking list emptiness, you can write more efficient, readable, and robust Python code.

Now that you’ve mastered how to find the length of a list, take your Python skills even further with these related tutorials:

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Safa Mulani
Safa Mulani
Author
Andrea Anderson
Andrea Anderson
Editor
Technical Editor
See author profile
Manikandan Kurup
Manikandan Kurup
Editor
Senior Technical Content Engineer I
See author profile

With over 6 years of experience in tech publishing, Mani has edited and published more than 75 books covering a wide range of data science topics. Known for his strong attention to detail and technical knowledge, Mani specializes in creating clear, concise, and easy-to-understand content tailored for developers.

Category:
Tags:

Still looking for an answer?

Was this helpful?
Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.