Need help with Python references


#1

Hello

I was writing code to reverse a doubly linked list and managed to solve it correctly but now I’m confused what python is actually doing here. Here is the code:

def reverse(self):
        print(self.head)
        current = self.head
        self.head, self.tail = self.tail, self.head
        while current:
            print(self.head)
            current.link, current.prev, current= current.prev, current.link, current.link
        print(self.head)
        return self

So I set current to the head and then I swapped the head and tail of the linked list. Thus current still referenced the original head (I think). Now this is where I’m confused. The two print statements of self.head are never the same. Within the for loop it still shows the tail but right when it leaves the loop it automatically turns into the correct linked list. Here’s is the output of an example.

0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> None
9 -> None
9 -> None
9 -> None
9 -> None
9 -> None
9 -> None
9 -> None
9 -> None
9 -> None
9 -> None
9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> 0 -> None

So now I am just curious how Python is doing this. Changing the next pointer and prev pointer of a variable actually changes the next pointer and prev pointer of the node it’s references right? So what is current referencing after I swapped the head and the tail and how does it manage to give the right answer?


#2

That variable still refers to the same object since you haven’t assigned it to anything else, yes.

I wouldn’t call it automatic, but do consider when the old tail gets its NEXT reference set (when it’ll start referring to node 8 instead of None)

Variables are just name tags, you aren’t changing anything to them, you’re changing what they refer to (your list node)