How to Check the Length of a List in Python: `len()` vs. `__len__()`
In Python, determining the number of elements in a list (its length) is a common operation. Python provides two primary methods to achieve this, offering flexibility based on preference and context.
1. Using the Built-in len()
Function
The most common and recommended way to get the length of a list in Python is by using the built-in len()
function. This function is versatile and can be used with various sequence types (like strings, tuples, and dictionaries) to return the number of items in them.
Example:
my_list = [1, 2, 3, 4, 5]
list_length = len(my_list)
print("List length:", list_length) # Output: List length: 5
The len()
function is straightforward, readable, and efficient for this purpose.
2. Accessing the __len__()
Dunder Method Directly
Every object in Python that supports the len()
function internally implements a special method called __len__()
(often referred to as a “dunder” method). You can directly call this method on a list object to retrieve its length.
Example:
my_list = [1, 2, 3, 4, 5]
list_length = my_list.__len__()
print("List length:", list_length) # Output: List length: 5
While this method yields the same result as len()
, it’s generally not the preferred approach for everyday coding. The len()
function is considered more Pythonic and is designed for clarity and ease of use. The __len__()
method is primarily for internal use by the Python interpreter and for developers who are implementing custom classes that need to support the len()
operation.
In summary, for checking the length of a list in Python, the len()
function is the standard and most readable choice. The __len__()
method provides an alternative for specific advanced scenarios.