I was creating a linked list and was adding a function to get an element at a given position.
I have attached my code below.
In the code I have
current = self.head. Here
current is assigned
self.head. So aren’t both of these same? In the
while loop when I used
while current the code works without any error:
def get_position(self, position): current = self.head counter =0 while current: counter+=1 current=current.next print("total elements:",counter)
But if I use
while self.head I get an error:
def get_position(self, position): current = self.head counter =0 while self.head: counter+=1 current=current.next print("total elements:",counter)
AttributeError: ‘NoneType’ object has no attribute ‘next’.
Please help me in understanding how both of these are different.
while self.head is a condition that will never change, because
self.head is not changed in the loop (and it shouldn’t). So this means that if it is true once, it will always be true.
You might mistakenly think that when a new assignment is made to
current, that this assignment also applies to
self.head, but that is not true. They are two separate references (an attribute and a variable) that just happen to reference the same node at the start of the loop. But if
current gets to reference a different node, this does not affect what
Compare it with this trivial situation:
a = b = 1 a = 2 print(b) # still 1.
The same principle holds with
current. An assignment to
current will not affect
Now to the exception: the loop’s body assigns new values to
At some point
current will reference the last node of the list and then
None. So when the above assignment happens again,
current will be
None. But the loop doesn’t end, as
self.head is unchanged (still references the first node), and so the next iteration will evaluate again
current.next, but that triggers an error, as
None has no attribute
while condition should be something that makes the loop exit when