Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Custom len() Function In Python
The len() function in Python returns the number of items in an object. You can create a custom version by iterating through any iterable and counting its elements.
How len() Works Internally
Python's built-in len() function calls the __len__() method of an object. For custom implementation, we iterate through elements and count them manually.
Creating a Custom Length Function
Basic Implementation
Here's how to implement a custom length function using iteration ?
def custom_length(iterable):
"""Calculate length of any iterable by counting elements"""
count = 0
for item in iterable:
count += 1
return count
# Test with different data types
text = "tutorialspoint"
numbers = [1, 2, 3, 4, 5]
data = (10, 20, 30)
print(f"Length of '{text}': {custom_length(text)}")
print(f"Length of {numbers}: {custom_length(numbers)}")
print(f"Length of {data}: {custom_length(data)}")
Length of 'tutorialspoint': 14 Length of [1, 2, 3, 4, 5]: 5 Length of (10, 20, 30): 3
Using Sum with Generator Expression
A more concise approach using sum() ?
def custom_length_v2(iterable):
"""Calculate length using sum and generator expression"""
return sum(1 for _ in iterable)
# Test the function
items = ['apple', 'banana', 'cherry']
print(f"Length using sum method: {custom_length_v2(items)}")
# Compare with built-in len()
print(f"Built-in len(): {len(items)}")
Length using sum method: 3 Built-in len(): 3
Handling Edge Cases
A robust custom length function should handle various scenarios ?
def robust_length(iterable):
"""Custom length function with error handling"""
try:
count = 0
for item in iterable:
count += 1
return count
except TypeError:
return "Error: Object is not iterable"
# Test with different inputs
print(f"String: {robust_length('hello')}")
print(f"List: {robust_length([1, 2, 3])}")
print(f"Empty list: {robust_length([])}")
print(f"Range: {robust_length(range(5))}")
print(f"Non-iterable: {robust_length(42)}")
String: 5 List: 3 Empty list: 0 Range: 5 Non-iterable: Error: Object is not iterable
Comparison
| Method | Performance | Memory Usage | Best For |
|---|---|---|---|
Built-in len()
|
Fastest (O(1)) | Minimal | Production code |
| Custom iteration | Slower (O(n)) | Low | Learning/understanding |
| Sum with generator | Slower (O(n)) | Very low | Functional programming |
Conclusion
Custom len() functions help understand how iteration works internally. While built-in len() is more efficient, custom implementations are useful for learning and handling special cases where standard length calculation isn't available.
