Python Forum

Full Version: Building a DoublyLinkedList in Python - - append method
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Greetings Pythonistas!

I am learning how to write basic algorithms in Python but am taking an unusual approach. I am taking a Udemy course which teaches algorithms in JavaScript. What I do is watch the lesson where the instructor uses an interactive and dynamic visual aid to explain how the algorithm’s feature works, provides the pseudo code, asks the student to try writing the script themselves, and then provides the solution in JavaScript. I follow along and do all of that except for the last step, I use Python instead of JS. Based on the pseudo code, I write the algorithm in Python. Afterwards, I look at the solution in JS and make modifications as necessary.

Below is my attempt at building a Doubly Linked List (DLL). So far I’ve written the base Node constructor, the DLL constructor, the DLL append method, and the DLL string method. Below I have also included some testing in my Python REPL shell.

Having said all of that, my script doesn’t work as intended. When I instantiate a test list object and try to append integers one at a time, Python is only recording the most recent value. The list is not being extended by each value. The old value is just being overwritten by the new one in place. Any idea why? What kind of changes do I need to make so that when I call the append method, the list increases by the value being entered?

class Node:
    # Create a new node with the value passed to the function
    def __init__(self, value):
        self.value = value
        self.next = None
        self.prev = None

class DoublyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        self.length = 0

    def append(self, value):
        # If the head property is null set the head and tail to be the newly created node
        newNode = Node(value)
        if self.length == 0:
            self.head = newNode
            self.tail = newNode
        # If not... 
        else:
            # Set the next property on the tail to be that node
            self.tail.next = newNode
            # Set the previous property on the newly created node to be the tail
            newNode.prev = self.tail
            # Set the tail to be the newly created node
            self.tail = newNode
        # Increment the length
        self.length = self.length + 1
        # Return the Doubly Linked List
        return self
    
    def __str__(self):
        current = self.head
        result = []
        while current:
            result.append(current.value)
            current = current.next
        return str(result)
$ python      
Python 3.11.6 (main, Nov 14 2023, 09:36:21) [GCC 13.2.1 20230801] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from script import Node,DoublyLinkedList
>>> DLL_obj = DoublyLinkedList().append(24)
>>> print(DLL_obj)
[24]
>>> DLL_obj = DoublyLinkedList().append(2)
>>> DLL_obj = DoublyLinkedList().append(256)
>>> print(DLL_obj)
[256]
>>> 
Your code is fine. The problem is you keep creating new lists, so each list is really length 1.
class Node:
    # Create a new node with the value passed to the function
    def __init__(self, value, prev=None, next=None):
        self.value = value
        self.next = next
        self.prev = prev
 

class DoublyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        self.length = 0
 
    def append(self, value):
        """Add value to tail."""
        node = Node(value, self.tail)
        if self.tail is not None:
            self.tail.next = node
        else:
            self.head = node
        self.tail = node
        self.length += 1
        return self

    def __len__(self):
        return self.length
     
    def __str__(self):
        values = []
        node = self.head
        while node:
            values.append(node.value)
            node = node.next
        return str(values)


x = DoublyLinkedList()
x.append(1).append(2).append(3)
print(x)
Output:
[1, 2, 3]
Hi @deanystad. Thank you for your reply. You are right that I wasn't calling my custom append() method properly in my shell. Not sure how I let that slip through my fingers.