Linked lists are a fundamental data structure in computer science and can be used in various real-world scenarios. In this tutorial, I’ll provide a simple example of implementing and using a singly linked list in Python, along with best practices.

Scenario: Imagine you’re building a music playlist application, and you want to create a playlist of songs. Each song will be represented as a node in a singly linked list. We’ll focus on the basic operations of adding songs to the playlist, removing songs, and displaying the playlist.

Here’s how you can create a linked list and implement these operations:

# Define a Node class to represent a song in the playlist
class Node:
    def __init__(self, title, artist):
        self.title = title
        self.artist = artist = None  # Reference to the next song in the playlist

# Define a Playlist class to manage the linked list of songs
class Playlist:
    def __init__(self):
        self.head = None  # Reference to the first song in the playlist

    def add_song(self, title, artist):
        new_song = Node(title, artist)
        if not self.head:
            self.head = new_song
            current_song = self.head
                current_song =
   = new_song

    def remove_song(self, title):
        if not self.head:
            return  # Playlist is empty
        if self.head.title == title:
            self.head =
        current_song = self.head
            if == title:
            current_song =

    def display_playlist(self):
        current_song = self.head
        if not current_song:
            print("Playlist is empty.")
        while current_song:
            print(f"{current_song.title} by {current_song.artist}")
            current_song =

# Create a playlist
my_playlist = Playlist()

# Add songs to the playlist
my_playlist.add_song("Song1", "Artist1")
my_playlist.add_song("Song2", "Artist2")
my_playlist.add_song("Song3", "Artist3")

# Display the playlist
print("Current Playlist:")

# Remove a song from the playlist

# Display the updated playlist
print("\nUpdated Playlist:")


Current Playlist:
Song1 by Artist1
Song2 by Artist2
Song3 by Artist3

Updated Playlist:
Song1 by Artist1
Song3 by Artist3

In this example, we define a Node class to represent individual songs and a Playlist class to manage the linked list of songs. The Playlist class includes methods to add, remove, and display songs. This is a simplified real-world example, but it illustrates the fundamental concepts of linked lists in Python.

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *