The NameError: name 'ListNode' is not defined is an error you'll commonly encounter when working with linked list problems. It occurs when Python can't find a definition for ListNode in the current scope.
In this guide, we'll cover all the common causes of this error and show you exactly how to fix each one with clear examples.
What Is a NameError?
A NameError in Python is raised when the interpreter encounters a name (variable, function, class, etc.) that hasn't been defined in the current scope. Python is an interpreted language that reads code top to bottom: if you reference something before it's defined, or if it was never defined at all, you'll get this error.
NameError: name 'ListNode' is not definedThis specifically means Python looked for something called ListNode and couldn't find it anywhere in the accessible scope.
Common Causes and Solutions
1. The ListNode Class Was Never Defined
The most straightforward cause: you're using ListNode but never defined it in your code. On platforms like LeetCode, the ListNode class is provided behind the scenes, but if you're running the code locally, you need to define it yourself.
❌ Wrong: Using ListNode without defining it:
def create_linked_list(values):
dummy = ListNode(0) # NameError: name 'ListNode' is not defined
current = dummy
for val in values:
current.next = ListNode(val)
current = current.next
return dummy.next
head = create_linked_list([1, 2, 3])Output:
NameError: name 'ListNode' is not defined✅ Correct: Define the ListNode class first:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def create_linked_list(values):
dummy = ListNode(0)
current = dummy
for val in values:
current.next = ListNode(val)
current = current.next
return dummy.next
head = create_linked_list([1, 2, 3])
current = head
while current:
print(current.val, end=" -> ")
current = current.next
print("None")Output:
1 -> 2 -> 3 -> None2. Capitalization Mismatch (Typo)
Python is case-sensitive. ListNode, Listnode, listnode, and LISTNODE are all different names. If you define the class with one casing but reference it with another, you'll get a NameError.
❌ Wrong: Class defined as Listnode, used as ListNode:
class Listnode: # Lowercase 'n'
def __init__(self, val=0, next=None):
self.val = val
self.next = next
node = ListNode(5) # Uppercase 'N': NameError!Output:
NameError: name 'ListNode' is not defined✅ Correct: Use consistent capitalization:
class ListNode: # PascalCase: Python convention for class names
def __init__(self, val=0, next=None):
self.val = val
self.next = next
node = ListNode(5) # Matches the class definition
print(node.val)Output:
53. Missing Import Statement
If ListNode is defined in a separate module (file), you need to import it before using it.
❌ Wrong: No import:
def reverse_list(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
node = ListNode(1) # NameError!✅ Correct: Import from the module:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = nextfrom list_node import ListNode # Import the class
def reverse_list(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
node3 = ListNode(3)
node2 = ListNode(2, node3)
node1 = ListNode(1, node2)
reversed_head = reverse_list(node1)
current = reversed_head
while current:
print(current.val, end=" -> ")
current = current.next
print("None")Output:
3 -> 2 -> 1 -> None4. Definition Order: Using Before Defining
Python reads code top to bottom. If you reference ListNode before its class definition appears, you'll get a NameError.
❌ Wrong: Using ListNode before defining it:
node = ListNode(10) # NameError!
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next✅ Correct: Define the class before using it:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
node = ListNode(10)
print(node.val)Output:
105. Scope Issues: Defined in a Different Scope
If ListNode is defined inside a function, it's not accessible outside that function:
❌ Wrong: Class defined inside a function:
def setup():
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
setup()
node = ListNode(5) # NameError: ListNode only exists inside setup()✅ Correct: Define the class at the module level:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def create_node(value):
return ListNode(value) # Accessible because it's defined at module level
node = create_node(5)
print(node.val)Output:
5Complete Working Example
Here's a full, self-contained example with a ListNode class and common linked list operations:
class ListNode:
"""Standard singly linked list node."""
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __repr__(self):
values = []
current = self
while current:
values.append(str(current.val))
current = current.next
return " -> ".join(values) + " -> None"
def list_to_linkedlist(lst):
"""Convert a Python list to a linked list."""
dummy = ListNode(0)
current = dummy
for val in lst:
current.next = ListNode(val)
current = current.next
return dummy.next
def reverse_linked_list(head):
"""Reverse a linked list in place."""
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
head = list_to_linkedlist([1, 2, 3, 4, 5])
print(f"Original: {head}")
reversed_head = reverse_linked_list(head)
print(f"Reversed: {reversed_head}")Output:
Original: 1 -> 2 -> 3 -> 4 -> 5 -> None
Reversed: 5 -> 4 -> 3 -> 2 -> 1 -> NoneQuick Debugging Checklist
When you encounter NameError: name 'ListNode' is not defined, check these items:
| # | Check | What to Look For |
|---|---|---|
| 1 | Is ListNode defined? |
Must be defined in your file or imported |
| 2 | Is the spelling correct? | ListNode ≠ Listnode ≠ listnode |
| 3 | Is it imported? | from module import ListNode if defined elsewhere |
| 4 | Is it defined before use? | Class definition must appear above where it's used |
| 5 | Is it in the right scope? | Should be at module level, not inside a function |
| 6 | Are you running locally? | LeetCode defines it for you; locally you must define it yourself |
Conclusion
The NameError: name 'ListNode' is not defined error simply means Python can't find a class or variable called ListNode in the current scope. The fix depends on the cause: define the class if it doesn't exist (especially when running LeetCode solutions locally), check your capitalization for typos, add an import statement if it's in another file, and ensure the definition appears before its usage in your code. Once you have the ListNode class properly defined and accessible, the error will resolve immediately.