Single Linked Lists Ex13

Hi guys, I am struggling with exercise 13 in the book “Learn More Python the Hard Way”. The issue lies in finding the logic by which the self.begin attribute in the controlling class keeps getting new nodes attached to it (resulting into etc. as the list grows). So the first if condition (in the script below) makes sense to me, but I am not seeing the logic in the else statement that could potentially bring the nodes from the end attribute to the begin attribute – as the else statement only targets the self.end attribute.

Below is the fragment from Zed Shaw’s github/video and I’ve also uploaded a flow chart on how I see the logic not making sense to me in extending the list. Basically used colors to differentiate between the nodes in the if, elif and finally else statement

Hope someone sees where I go wrong in the though proces.

class SingleLinkedList(object):

    def __init__(self):
        self.begin = None
        self.end = None

    def push(self, obj):
        """Appends a new value on the end of the list."""
        node = SingleLinkedListNode(obj, None)
        if self.begin == None:
            # nothing net
            self.begin = node
            self.end = self.begin
        elif self.begin == self.end:
   = node
            self.end = node
   = node
            self.end = node
            assert self.begin != self.end

assert == None

Ok, so the piece you’re missing is the three conditions that the if-statement is handling:

  1. “If the list is empty” which is self.begin == None. In this case I simply set both begin and end to the node.
  2. “If the list had one element.” Then just add that to and move end to it.
  3. “Else, more than 1 elements.” Now we come to where you’re getting tripped up. You’re looking at self.begin, but after 1 element there’s just operations on self.end. This code sets to the next node, thus extending the list, and then moves self.end there.

Study those to see why I did it like that.

Many thanks for your response!

I got it now. I had a misunderstanding in how I perceived the attributes and the subsequent action performed on them. Referring to the operation in the IF statement as linking both attributes to the same node is what I needed to know. Thanks :slight_smile:

Keep up the great work!

1 Like