Constructing a Singly-Linked-List (Python)

Alan Banks
3 min readAug 15, 2020

--

A brief and quick implementation with Python :)

Hello everyone, if you are not already aware, this LinkedList implementation is part of a series I am doing on Linked List in different programming languages.
Feel free to check out the other linked list implementations I’ve created with Javascript and Ruby.

If you are already familiar feel free to just skip the “What is a Linked List” heading below .

What is a Linked List?

A linked list is a data structure in which each element is a node and it contains two types of information.
1) It’s data
2) a reference/pointer to another node within a list.

To dive into more specifics, you can have a singly-linked-list where it would typically have the attributes:
value (data)
next (pointer)

And a doubly-linked-list in which it would have:
value (data)
next (pointer)
previous (pointer)

Creating a Singly-Linked-List in Python

In order to create a linked list from scratch you need to construct two classes.

1) Node Class
This should be able to create a node object that possesses the attributes: Value and Next.

A Basic Node Class Implementation in Python syntax

2) LinkedList Class
This should be able to create a LinkedList object which will consist of Node Class objects and also possess the variable/attribute: Head (which is the starting point of the list).

Additionally it should have a method responsible for adding onto the list or an append method.

Other methods can be added optionally.

A Basic Linked List Class Implementation in Python syntax

Putting it all together and Testing it out:

Let’s talk about the main method and what’s happening:

  1. Starting off (line 35) we can see we initialized our list with a Node with a value of 2. This Node will also be seen as the initial head of the linked list.
  2. After initializing our list, we then add two nodes with the values 3 and 5, in order.
  3. After adding those 2 nodes, we finally use our custom insertBeginning method to create a new Head Node in our list.

Putting the 3 together we can see that our print_list() method prints out the Nodes in the expected ascending order, based upon the values associated with each node.

Feel free to see the Python code yourself on my github! This repo also contains different Linked Lists implementations in different languages.

Github Repo: https://github.com/alanbanks229/linked_lists/blob/master/singly_linked_list.rb

--

--