How To Find the Length of a List in Python
The length of a list refers to the number of elements in the list. There are several methods to determine the length of a list in Python. For example, consider a list l = [1, 2, 3, 4, 5], length of this list is 5 as it contains 5 elements in it. Let's explore different methods to find the length of a list with examples.
Using len()
len() function is a built-in Python function and it's the simplest and most efficient way to find the length of a list in Python. It can be used on any sequence or collection, including lists.
a = [1, 2, 3, 4, 5]
print(len(a))
Output
5
Explanation: len() function directly returns the total number of elements present in the list.
Using loop (Naive method)
This approach involves manually iterating through the list and counting each element. It demonstrates how list traversal works but is less efficient than using built-in functions.
a = [1, 2, 3, 4, 5]
c = 0
for val in a:
c += 1
print(c)
Output
5
Explanation:
- counter 'c' is initialized to 0.
- each item in the list increments the counter by 1.
- final count gives the length of the list.
Using length_hint() from operator Module
length_hint() function, available in the operator module, returns an estimated length of an iterable. It’s useful in cases where the object doesn't support len(), but still exposes an estimated size.
from operator import length_hint
a = [1, 2, 3, 4, 5]
print(length_hint(a))
Output
5
Explanation:
- length_hint() function estimates the number of elements.
- in most cases, especially with lists, it returns the same value as len().
Note: While length_hint() works for built-in containers like lists, it's more useful for custom objects or iterators that don't directly support len().