Python Program to Find the Length of a List using Recursion

This is a Python Program to find the length of a list recursively.

Problem Description

The program takes a list and finds the length of the list recursively.

Problem Solution

1. Define a recursive function which takes a list as the argument.
2. Initialize a variable to a list.
3. In the function, put the condition that if it is not the original list, return 0.
4. Otherwise, recursively call the function to find the length of the list.
5. Print the final result of the string.
6. Exit.

Program/Source Code

Here is source code of the Python Program to find the length of a list recursively. The program output is also shown below.

def length(lst):
    if not lst:
        return 0
    return 1 + length(lst[1::2]) + length(lst[2::2])
a=[1,2,3]
print("Length of the string is: ")
print(a)
Program Explanation

1. Define a recursive function which takes a list as the argument.
2. Initialize a variable to a list.
3. In the function, put the condition that if it is not the original list, return 0.
4. Otherwise, recursively call the function to find the length of the list.
5. Print the final result of the string.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Length of the string is: 
[1, 2, 3]

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Note: Join free Sanfoundry classes at Telegram or Youtube

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.