'why I'm getting AttributeError: 'NoneType' object has no attribute 'value' when printing values without loop
I've worked on data structures in C++, now I've switched to python and facing an issue here.
When I try to access values of node without loop it always through an error AttributeError: 'NoneType' object has no attribute 'value'
def solution(l):
head=ListNode(None)
head.next=l
current=head.next #also tried head.next.next gets error on this one too
print(current.value)
return True
But when I try to print values in loop all the values are printed and I don't understand the science behind it
def solution(l):
head=ListNode(None)
head.next=l
current=head
while(current):
print(current.value)
current=current.next
return True
and here is the output of it printed output
Given that rest of the syntax is correct
Defined Node format is as follow:
# def __init__(self, x):
# self.value = x
# self.next = None
Now my question is why it prints values in loop and not in single line statment
Solution 1:[1]
Assuming that l is an instance of ListNode here.
You must always verify that a variable is not None before accessing one of its attributes (such as next).
The second solution does this every time a an assignment is made to current. It will exit the loop as soon as current is None.
The first solution will often work, except when an empty list is passed as argument, i.e. when l is None. Then it will trigger the error you mentioned. In that case also current will be None, and then accessing current.next is invalid.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | trincot |
