Skip to main content

Command Palette

Search for a command to run...

Example of Using a Linked List in Python

Updated
2 min read
Example of Using a Linked List in Python

Instead of just going through a class and trying to complete it, which can be a big trap, the best way to internalize concepts is by completing micro projects focused on the current topic in the class. I was unsure about linked lists, and in an attempt to get a better grasp on working with them, I created a small Python script to practice linked lists.

The File Structure

. ├── init.py ├── main.py └── playlist ├── init.py ├── node.py ├── playlist.py └── pycache ├── init.cpython-313.pyc ├── node.cpython-313.pyc └── playlist.cpython-313.pyc

The Node Class

This class represents only one song. It simply holds the song's title and points to the next song in the playlist.

class Node:
    def __init__(self, title):
         self.title = title #the song's title
         self.next = None #points to next song in the playlist

    def __repr__(self):
        return f"Node(title='{self.title}')"

The Playlist Class

This class manages the entire list of songs. It tracks where the first song is "head" and where the last song is "tail". This allows us to quickly add songs to the end.

add_song()

This function adds a new song to the end playlist.

def add_song(self, title):
        new_song = Node(title)

        if self.head is None:
            self.head = new_song
            self.tail = new_song
        else:
            self.tail.next = new_song
            self.tail = new_song

show_playlist()

This function iterates through every song in the playlist from the head t the tail and prints each song's title.

def show_playlist(self):
        current_node = self.head

        if current_node is None:
            print("The playlist is empty")
            return
        print("Your playlist!")

        while current_node:
            print(f"- {current_node.title}")
            current_node = current_node.next

Conclusion

In conclusion, working with linked lists in Python can be a valuable exercise for understanding data structures and improving programming skills. By creating a small project, such as a playlist manager, you can gain hands-on experience with linked lists, reinforcing the concepts learned in class. This approach not only helps in grasping the theoretical aspects but also in applying them practically, making the learning process more effective and engaging.