# Python Program to Find the Length of the Linked List using Recursion

PythonServer Side ProgrammingProgramming

When it is required to find the length of a linked list with the help of recursion, a method to add elements to the linked list, and a method to calculate the length of the linked list is defined. A helper function is defined that is called with the help of the previously defined length calculation method.

Below is a demonstration for the same −

## Example

Live Demo

class Node:
def __init__(self, data):
self.data = data
self.next = None

def __init__(self):
self.last_node = None

if self.last_node is None:
else:
self.last_node.next = Node(my_data)
self.last_node = self.last_node.next

def calculate_length(self):

def length_helper_fun(self, curr):
if curr is None:
return 0
return 1 + self.length_helper_fun(curr.next)

my_data = input('Enter elements of the linked list ').split()
for elem in my_data:
print('The length of the linked list is ' + str(my_instance.calculate_length()))

## Output

Enter elements of the linked list 12 45 32 67 88 0 99
The length of the linked list is 7

## Explanation

• The ‘Node’ class is created.

• Another ‘my_linked_list’ class with required attributes is created.

• It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’ and last node to ‘None’.

• Another method named ‘add_value’ is defined, that is used to add data to the linked list.

• Another method named ‘calculate_length’ is defined that is used to call the helper function to find the length of the linked list.

• The helper function is defined, since recursion needs to be used here.

• It checks for the current value of node, and returns the length of the list.

• An object of the ‘my_linked_list’ class is created.

• The user input is taken for the elements in the linked list.

• Methods are called on it to add data.

• The calculate_length method is called, and output is displayed on the console.