Search code examples
python-3.xlinked-listsingly-linked-listreversing

Understanding the "self" in classes for Python


I'm trying to understand the solution provided for reversing a linked list. In particular, I don't get why for the very last line we write:

self.head=prev

and not

current=prev

since

current=self.head

I know my reasoning is flawed, that's why I came here for help. Thank you in advance.

class Node: 

    # Constructor to initialize the node object 
    def __init__(self, data): 
        self.data = data 
        self.next = None

class LinkedList: 

    # Function to initialize head 
    def __init__(self): 
        self.head = None
  def reverse(self): 
        prev = None
        current = self.head 
        while(current is not None): 
            next = current.next
            current.next = prev 
            prev = current 
            current = next
        self.head = prev 

Solution

  • = is not equality like in math, it is the assignment/binding operator.

    Therefore, after:

    current=self.head
    current=prev
    

    current will have the value of prev and self.head will have nothing to do with current nor will be modified.