Python Program to Find the Length of a List using Recursion

1. Introduction

Recursion is a powerful concept in programming where a function calls itself to solve a problem. In Python, we can use recursion to perform many operations on lists, including finding the length of the list.

Definition

The length of a list refers to the number of items it contains. To find this recursively, the process involves counting the first element and then recursively counting the rest of the list.

2. Program Steps

1. Define a function that uses recursion to count the length of the list.

2. If the list is empty, return 0.

3. Otherwise, return 1 plus the length of the list minus the first element.

4. Print the result from the recursive function.

3. Code Program

# Step 1: Define the recursive function
def recursive_length(lst):
    # Step 2: Check if the list is empty
    if not lst:
        return 0
    # Step 3: Count the first element and recursively call the function for the remaining list
    else:
        return 1 + recursive_length(lst[1:])

# Step 4: Call the function with a list and print the result
my_list = [1, 2, 3, 4, 5]
length_of_list = recursive_length(my_list)
print(f"The length of the list is: {length_of_list}")

Output:

The length of the list is: 5

Explanation:

1. recursive_length is a function that calculates the length of lst by recursion.

2. The function checks if lst is empty; if so, it returns 0, as an empty list has a length of 0.

3. If the list is not empty, the function counts one for the first element and adds it to the result of recursive_length(lst[1:]), which is a recursive call with the rest of the list.

4. my_list is defined with five elements.

5. length_of_list holds the result of the recursive_length function call, which is the length of my_list.

6. The print statement displays length_of_list, which is 5, confirming that my_list contains five elements.

Comments