Python : why doesn't a.pop() modify the list (custom linked-list class)
<p>I'm trying to define a class Hlist of linked lists as below:</p>

<pre><code>class Hlist:

def __init__(self, value, hlnext):
    self.value = value
    self.hlnext = hlnext

def pop(self):
    res = self.value
    if not(self.hlnext == None):
        self = self.hlnext
    return res

def __repr__(self):
    return (str(self.value) + ' - ' +  str(self.hlnext))
</code></pre>

<p>When I test the pop() method on </p>

<pre><code>a = Hlist(1, Hlist(2, None))
</code></pre>

<p>Python returns 1 - 2 - None, ok. Then</p>

<pre><code>a.pop()
</code></pre>

<p>returns 1, fine. However : </p>

<pre><code>print(a)
</code></pre>

<p>returns 1 - 2 - None. The list hasn't been modified despite</p>

<pre><code>self = self.hlnext
</code></pre>

<p>Is self the pointer a or is it another pointer pointing to the same address as a?
And why does the following code return the expected answer for pop():</p>

<pre><code>class Hlist:

def __init__(self, value, hlnext):
    self.value = value
    self.hlnext = hlnext

def pop(self):
    res = self.value
    if not(self.hlnext == None):
        self.value = self.hlnext.value
        self.next = self.hlnext.hlnext
    return res

def __repr__(self):
    return (str(self.value) + ' - ' +  str(self.hlnext))
</code></pre>

<p>is it due to the setattr function used by python?</p>

<p>Actually i was trying to get the equivalent in Python of the following class in Java : </p>

<pre><code>class Hlist{
    int value;
    Hlist hlnext;

    Hlist(int value,Hlist hlnext){
        value = value;
        hlnext = hlnext;
    }
}
</code></pre>

<p>and add a pop() method to it. In a pop() method, will Java's <code>this</code> work the same way Python's <code>self</code> does (local variable) or will it be binded to the pointer a I called pop()? In that case, will <code>this = this.hlnext</code> change the <code>a</code> pointer or not?</p>

<p>It's moslty because you can't change self directly.<br>
If you think about pointers, you can't change the pointer address, except if you use a pointer on this pointer. Here, if you consider self as a pointer, when you assign another value to self, you don't really change the self pointer.</p>

<p><a href="http://stackoverflow.com/a/1216361/5813357">See this answer</a></p>

<p>The second code "works" (not in all cases), because you aren't changing self itself, but the references on which it's pointing. Then your instance is updated to remove its old value and update itself with the next value.</p>

python pointers linked-list