Python Program to Find the Length of a List Using Recursion

PythonServer Side ProgrammingProgramming

When it is required to find the length of a list with the help of recursion technique, a user defined method is used, and simple indexing technique is used.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem.


Below is a demonstration for the same −

 Live Demo

def list_length(my_list):
   if not my_list:
      return 0
   return 1 + list_length(my_list[1::2]) + list_length(my_list[2::2])
my_list = [1, 2, 3, 11, 34, 52, 78]
print("The list is :")
print("The length of the string is : ")


The list is :
[1, 2, 3, 11, 34, 52, 78]
The length of the string is :


  • A method named ‘list_length’ is defined, that takes a list as a parameter.
  • If the list is not present, the method returns 0.
  • Otherwise, it is indexed, and incremented by 1 and returned as output.
  • Outside the function, a list is defined, and is displayed on the console.
  • The method is called by passing this list as a parameter.
  • The output is then displayed on the console.
Published on 12-Mar-2021 16:59:04