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
Program to find length of a list without using built-in length() function in Python
Finding the length of a list without using built-in functions like len() is a common programming exercise. We can achieve this using several creative approaches including loops, mapping, and recursive methods.
So, if the input is like nums = [5,7,6,4,6,9,3,6,2], then the output will be 9.
Method 1: Using map() and sum()
We can map each element to 1 and then sum the results ?
def find_length_map(nums):
return sum(map(lambda x: 1, nums))
nums = [5, 7, 6, 4, 6, 9, 3, 6, 2]
print("Length using map():", find_length_map(nums))
Length using map(): 9
Method 2: Using for loop
A simple counter approach iterating through each element ?
def find_length_loop(nums):
count = 0
for item in nums:
count += 1
return count
nums = [5, 7, 6, 4, 6, 9, 3, 6, 2]
print("Length using loop:", find_length_loop(nums))
Length using loop: 9
Method 3: Using enumerate()
We can use enumerate() to get the index and find the last index ?
def find_length_enumerate(nums):
for i, item in enumerate(nums):
pass
return i + 1 if nums else 0
nums = [5, 7, 6, 4, 6, 9, 3, 6, 2]
print("Length using enumerate():", find_length_enumerate(nums))
# Test with empty list
empty_list = []
print("Length of empty list:", find_length_enumerate(empty_list))
Length using enumerate(): 9 Length of empty list: 0
Method 4: Using recursion
A recursive approach that counts elements one by one ?
def find_length_recursive(nums):
if not nums:
return 0
return 1 + find_length_recursive(nums[1:])
nums = [5, 7, 6, 4, 6, 9, 3, 6, 2]
print("Length using recursion:", find_length_recursive(nums))
Length using recursion: 9
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
map() + sum() |
O(n) | O(n) | Functional programming style |
| For loop | O(n) | O(1) | Most readable and efficient |
enumerate() |
O(n) | O(1) | When you need index information |
| Recursion | O(n) | O(n) | Learning recursion concepts |
Conclusion
The simple for loop approach is most efficient with O(1) space complexity. Use map() for functional programming style, and recursion for educational purposes, though it may cause stack overflow for large lists.
