Junior — Middle
Is it possible to use the built-in len() function to determine the length of a singly linked list in Python?
sobes.tech AI
Answer from AI
The built-in len() function in Python does not work for singly linked lists if they are implemented manually (for example, through nodes with a pointer to the next element). len() works with sequences and collections that implement the __len__() method.
If you have a singly linked list class, to get its length, you need to either:
- Store a counter of elements inside the class and update it when adding/removing elements
- Or traverse all nodes and count manually
Example of counting the length of a singly linked list:
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def length(self):
count = 0
current = self.head
while current:
count += 1
current = current.next
return count
Therefore, len() cannot be used directly unless you implement the __len__ method in the list class.