
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Length of a Linked List in Python
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
class ListNode: def __init__(self, data, next = None): self.val = data self.next = next def make_list(elements): head = ListNode(elements[0]) for element in elements[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = ListNode(element) return head class Solution: def solve(self, node): count = 0 while node: count +=1 node=node.next return count ob = Solution() head = make_list([2,4,5,7,8,9,3]) print(ob.solve(head))
Input
[2,4,5,7,8,9,3]
Output
7
- Related Articles
- JavaScript Program for Finding Length of a Linked List
- Find length of loop in linked list in C++
- Python Program to Find the Length of the Linked List using Recursion
- Find Length of a Linked List (Iterative and Recursive) in C++
- Check whether the length of given linked list is Even or Odd in Python
- Python Program to Find the Length of the Linked List without using Recursion
- A strictly increasing linked list in Python
- Palindrome Linked List in Python
- Reverse Linked List in Python
- Linked List Cycle in Python
- Delete Node in a Linked List in Python
- C program to find the length of linked list
- Program to find linked list intersection from two linked list in Python
- JavaScript Program for Finding the Length of Loop in Linked List
- Program to reverse a linked list in Python

Advertisements