TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: How to Create Linked Lists in Python
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python OOPPython Tutorials

How to Create Linked Lists in Python

Last updated: Jun 01, 2024 10:08 pm
By Meenakshi Agarwal
Share
8 Min Read
Getting Started with Linked Lists in Python
SHARE

Linked lists are like a series of connected boxes, where each box holds a piece of information and points to the next box. Let’s understand how to create and use Linked lists in Python.

Contents
What is a Linked List?Types of Linked ListsSingly Linked ListDoubly Linked ListCircular Linked ListImplementing Linked Lists in PythonSingly Linked List ExampleDoubly Linked List ExampleCircular Linked List ExampleCommon Linked List Operations in PythonSearching in a Linked ListDeleting from a Linked ListReversing a Linked ListPros and Cons of Linked ListsUse Cases in PythonChoosing the Right Type

Linked Lists Made Simple in Python

They’re a cool way to organize data in Python. Let’s check out how to use linked lists in Python in a simple and friendly way.

What is a Linked List?

Imagine you have a string of boxes, and each box has a number inside. These boxes are a linked list. Instead of standing in a line like arrays, linked list boxes are scattered around, and each box knows where the next one is.

Also Read: Python HeapQ Explained with Examples

Types of Linked Lists

Singly Linked List

Imagine a line of people holding hands. Each person (node) holds the hand of the person in front. This is a single link list. Check on the below code illustrating the simple doubly linked list. Please note the cell in the below code represents a node in the link list.

# Creating a singly linked list
cell1 = Cell(1)
cell2 = Cell(2)
cell3 = Cell(3)
cell1.next = cell2
cell2.next = cell3

Doubly Linked List

Now, picture a line where each person holds hands with the person in front and behind. This is a doubly linked list. The below is a logical representation of a doubly linked list in Python.

# Creating a doubly linked list
cell1 = Cell(1)
cell2 = Cell(2)
cell3 = Cell(3)

cell1.next = cell2
cell2.prev = cell1
cell2.next = cell3
cell3.prev = cell2

Circular Linked List

Imagine a group of people in a circle, holding hands with the person next to them and the last person holding hands with the first. This is a circular linked list.

Here is a simple demonstration of a circular link list in Python.

# Creating a circular linked list
cell1 = Cell(1)
cell2 = Cell(2)
cell3 = Cell(3)

cell1.next = cell2
cell2.next = cell3
cell3.next = cell1

Must Read: How to Create and Use Arrays in Python

Implementing Linked Lists in Python

Firstly, before we start, let’s create a helper, the Cell class, which represents each node in our linked list.

class Cell:
    def __init__(self, value):
        self.value = value
        self.next = None

Secondly, we’ll use the above class in all of the examples of this tutorial. We’ll derive other link list classes from it.

Singly Linked List Example

Now, let’s create a simple singly linked list that points from one box to the next.

class SinglyLkdList:
    def __init__(self):
        self.head = None

    def append(self, data):
        new_node = Cell(data)
        if not self.head:
            self.head = new_node
            return
        current = self.head
        while current.next:
            current = current.next
        current.next = new_node

    def disp(self):
        elements = []
        current = self.head
        while current:
            elements.append(current.data)
            current = current.next
        print(" -> ".join(map(str, elements)))

Let’s use this linked list:

sin_list = SinglyLkdList()
sin_list.append(1)
sin_list.append(2)
sin_list.append(3)

sin_list.disp()
# Output: 1 -> 2 -> 3

Doubly Linked List Example

Now, let’s enhance our linked list to remember the person behind too.

class DoublyLkList:
    def __init__(self):
        self.head = None

    def append(self, data):
        new_node = Cell(data)
        if not self.head:
            self.head = new_node
            return
        current = self.head
        while current.next:
            current = current.next
        current.next = new_node
        new_node.prev = current

    def disp(self):
        elements = []
        current = self.head
        while current:
            elements.append(current.data)
            current = current.next
        print(" <-> ".join(map(str, elements)))

Let’s use this doubly linked list:

dob_list = DoublyLkList()
dob_list.append(1)
dob_list.append(2)
dob_list.append(3)

dob_list.disp()
# Output: 1 <-> 2 <-> 3

Circular Linked List Example

Lastly, let’s create a circular linked list, a fun loop of holding hands.

class CircularLkdList:
    def __init__(self):
        self.head = None

    def append(self, data):
        new_node = Cell(data)
        if not self.head:
            self.head = new_node
            new_node.next = self.head
            return
        current = self.head
        while current.next != self.head:
            current = current.next
        current.next = new_node
        new_node.next = self.head

    def disp(self):
        elements = []
        current = self.head
        while True:
            elements.append(current.data)
            current = current.next
            if current == self.head:
                break
        print(" -> ".join(map(str, elements)))

Let’s use this circular linked list:

cir_list = CircularLkdList()
cir_list.append(1)
cir_list.append(2)
cir_list.append(3)

cir_list.disp()
# Output: 1 -> 2 -> 3 -> 1

Common Linked List Operations in Python

In this section, we added Python examples to demonstrate the common linked list operations. You can perform them on the link lists.

Searching in a Linked List

Imagine finding a person in our line of linked boxes. Let’s create a simple way to search for a specific number.

def search_list(self, key):
    current = self.head
    while current:
        if current.data == key:
            return True
        current = current.next
    return False

Deleting from a Linked List

Imagine removing a person from our line. Let’s create a way to delete a specific number.

def del_list_item(self, key):
    current = self.head
    prev = None
    while current:
        if current.data == key:
            if prev:
                prev.next = current.next
            else:
                self.head = current.next
            return
        prev = current
        current = current.next

Reversing a Linked List

Imagine flipping our line of people around. Let’s create a way to reverse our linked list.

def rev_list(self):
    current = self.head
    prev = None
    while current:
        next_node = current.next
        current.next = prev
        prev = current
        current = next_node
    self.head = prev

Pros and Cons of Linked Lists

Pros:

  • Dynamic Size: Linked lists can grow or shrink during runtime.
  • Easy Insertion/Deletion: Adding or removing elements is efficient.

Cons:

  • Random Access is Slow: Accessing an element at a specific index takes time.
  • Extra Memory Usage: Each element requires extra space for the pointer.

Use Cases in Python

Here are some common scenarios where linked lists can be useful in Python.

  • When Size is Unknown: Linked lists are great when you don’t know the size of your data in advance.
  • Frequent Insertions/Deletions: If your program involves a lot of adding or removing elements, linked lists can be more efficient than arrays.

Choosing the Right Type

  • Singly Linked List: Use when traversal is mainly forward, and memory efficiency is a concern.
  • Doubly Linked List: Use when backward traversal is needed or when insertion/deletion at both ends is frequent.
  • Circular Linked List: Use when the data needs to be accessed in a loop.

Before you leave, render your support for us to continue. If you like our tutorials, share this post on social media like Facebook/Twitter.

Happy coding,
TechBeamers.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Micoservice Monitoring Tools for Testing and Debugging 7 Microservice Monitoring Tools You Should Use
Next Article Different Ways to Loop Through a Dictionary in Python with Examples Multiple Ways to Loop Through a Dictionary in Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x