I am facing problem in linked list in python

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’.

In second image I use while self.head. Here I got error

Please help me in understanding how both of these are different.

Answer

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 self.head references.

Compare it with this trivial situation:

a = b = 1
a = 2 
print(b)  # still 1.

The same principle holds with self.head and current. An assignment to current will not affect self.head.

Now to the exception: the loop’s body assigns new values to current:

current=current.next

At some point current will reference the last node of the list and then current.next is 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 next.

Conclusion, your while condition should be something that makes the loop exit when current is None.