Python Program to Find the Length of a List using Recursion

Python Program to Find the Length of a List using Recursion | The length of a list is the number of elements in a list, there are many methods to find python list size. The list is a container that has many elements of similar data types.

How to Get the Length of a List in Python using Recursion

The process of calling the same function, again and again, is called recursion, this reduces the length of the code and also makes it easy for the programmer. Let us see the code to find the size of a list in python.

# Python program to find the length of a list using recursion

# user-defined function
len = 0
def length(a):
   global len
   if a:
      len = len + 1
      length(a[1:])
   return len

# take list
a = [1, 2, 3, 4, 5, 6]

# calling function
len = length(a)

# print length of the list
print("The length of a list is", len)

Output:-

The length of a list is 6

Python Program to Find the Length of a List using Recursion

In the previous program, we will find the length of numbers in a list but in this program, we will find the length of strings in a list using recursion.

# Python program to find the length of a list using recursion

# user-defined function
len = 0
def length(a):
   global len
   if a:
      len = len + 1
      length(a[1:])
   return len

# take list
a = ['Hello', 'Welcome', 'to', 'Know', 'Program']

# calling function
len = length(a)

# print length of the list
print("The length of a list is", len)

Output:-

The length of a list is 6

Python Program to Get Size of List using Recursion

This python program performs the same task but different input values. Here, we will give both numbers and strings in a list.

# Python program to find the length of a list using recursion

# user-defined function
len = 0
def length(a):
   global len
   if a:
      len = len + 1
      length(a[1:])
   return len

# take list
a = [0, 'Hello', 1, 'Know', 2, 'Program', 3]

# calling function
len = length(a)

# print length of the list
print("The length of a list is", len)

Output:-

The length of a list is 6

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *