Python Program to Find the Length of a List Using Recursion

When it is required to find the length of a list using recursion, a user-defined method is used along with simple indexing technique. This approach demonstrates how recursion can solve problems by breaking them into smaller subproblems.

A list can store heterogeneous values (i.e., data of any data type like integer, floating point, strings, and so on). Recursion computes output of small bits of the bigger problem and combines these bits to give the solution to the bigger problem.

Method 1: Using Simple Recursion

The most straightforward recursive approach processes one element at a time ?

def list_length_simple(my_list):
    if not my_list:
        return 0
    return 1 + list_length_simple(my_list[1:])

my_list = [1, 2, 3, 11, 34, 52, 78]
print("The list is:")
print(my_list)
print("The length of the list is:")
print(list_length_simple(my_list))
The list is:
[1, 2, 3, 11, 34, 52, 78]
The length of the list is:
7

Method 2: Using Divide and Conquer

A more efficient approach that divides the list into two halves ?

def list_length_divide(my_list):
    if not my_list:
        return 0
    if len(my_list) == 1:
        return 1
    
    mid = len(my_list) // 2
    return list_length_divide(my_list[:mid]) + list_length_divide(my_list[mid:])

my_list = [1, 2, 3, 11, 34, 52, 78]
print("The list is:")
print(my_list)
print("The length of the list is:")
print(list_length_divide(my_list))
The list is:
[1, 2, 3, 11, 34, 52, 78]
The length of the list is:
7

How It Works

Both methods use recursion with a base case and recursive case:

  • Base case: If the list is empty, return 0
  • Recursive case: Add 1 for the current element and recursively call the function on the remaining elements

The divide-and-conquer method splits the problem more evenly, potentially reducing the recursion depth.

Comparison

Method Time Complexity Space Complexity Recursion Depth
Simple Recursion O(n) O(n) n
Divide and Conquer O(n) O(log n) log n

Conclusion

While Python's built-in len() function is more efficient, these recursive approaches demonstrate fundamental recursion concepts. The divide-and-conquer method is preferred for large lists as it has lower recursion depth.

Updated on: 2026-03-25T17:36:49+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements