# Length of a Linked List in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a singly linked list, we have to find its length. The linked list has fields next and val.

So, if the input is like [2 -> 4 -> 5 -> 7 -> 8 -> 9 -> 3], then the output will be 7.

To solve this, we will follow these steps −

• count := 0
• while node is non null, do
• count := count + 1
• node:= next of node
• return count

Let us see the following implementation to get better understanding −

## Example

Live Demo

class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
def make_list(elements):
for element in elements[1:]:
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
class Solution:
def solve(self, node):
count = 0
while node:
count +=1
node=node.next
return count
ob = Solution()
print(ob.solve(head))
[2,4,5,7,8,9,3]
7