The Wayback Machine - https://web.archive.org/web/20240910154553/https://www.geeksforgeeks.org/pretty-print-linked-list-in-python/
Open In App

Pretty print Linked List in Python

Last Updated : 26 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Creating custom data types can be tricky, especially when you want to use it like any other data type. Linked List can be thought of as an example of a custom data type. In other languages, if you want to print the linked list, you would define a separate print function, something like pprint but it looks kind of odd, right? Like it would be great to have the default print function do the same, right? Well, that’s where Python comes in. Python has some amazing methods called Dunder methods. 

Dunder methods

Dunder stands for double under methods. Basically, any methods that start and end with double underscores are called Dunder methods or Magic methods. One such example of Dunder method is __init__. One similar method is __str__, which we are going to use in this article. This method can be used for pretty-printing in Python. Pretty print is nothing but applying various kinds of styles and formatting the content to be printed. Learn more about dunder methods here.

__str__ methods specify what should be returned from a class when that class is printed using the standard print function. Using this concept, we can have a lot of better representation of custom datatype. Here, below is an example of such custom representation. Note that the focus is on the Linked List implementation but more on the pythonic way of representing it. 

Example: Pretty print a singly linked list 10->15->20 as [10, 15, 20]

Python3




class Node:
    def __init__(self, val=None):
        self.val = val
        self.next = None
 
 
class LinkedList:
    def __init__(self, head=None):
        self.head = head
 
    def __str__(self):
       
        # defining a blank res variable
        res = ""
         
        # initializing ptr to head
        ptr = self.head
         
       # traversing and adding it to res
        while ptr:
            res += str(ptr.val) + ", "
            ptr = ptr.next
 
       # removing trailing commas
        res = res.strip(", ")
         
        # chen checking if
        # anything is present in res or not
        if len(res):
            return "[" + res + "]"
        else:
            return "[]"
 
 
if __name__ == "__main__":
   
    # defining linked list
    ll = LinkedList()
 
    # defining nodes
    node1 = Node(10)
    node2 = Node(15)
    node3 = Node(20)
 
    # connecting the nodes
    ll.head = node1
    node1.next = node2
    node2.next = node3
     
    # when print is called, by default
    #it calls the __str__ method
    print(ll)


Output

[10, 15, 20]

Time complexity: O(n), where n is the number of nodes in the linked list. 

Auxiliary space: O(1). 

Note that when printing the class, __str__ is called by default. This is the magic of Python. The main purpose of this article is to show how small little magic methods can make your lives a lot easier. 



Previous Article
Next Article

Similar Reads

Pretty Print JSON in Python
JSON is a javascript notation of storing and fetching the data. Data is usually stored in JSON, XML or in some other database. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Read, Write and Parse JSON using Python Pretty Print JSON Whenever d
2 min read
Python - Pretty Print JSON
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will learn about JSON pretty print What is JSON?JSON (JavaScript Object Notation) is a text-based data format that is interchangeable with many programming languages.
5 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
How to Pretty Print an Entire Pandas Series or DataFrame?
In this article, we are going to see how to Pretty Print the entire pandas Series / Dataframe. There are various pretty print options are available for use with this method. Here we will discuss 3 ways to Pretty Print the entire Pandas Dataframe: Use pd.set_options() methodUse pd.option_context() methodUse options.display() MethodCreating DataFrame
3 min read
Pretty Printing XML in Python
XML stands for Extensible Markup Language and is used to encode a document that can be understandable by both humans and machines. Data stored in XML format is easy to understand and easy to modify. There are three main things that have to keep in mind when you are using XML – Simplicity, Generality, and Usability. Pretty Printing XML using xml.dom
2 min read
pprint : Data pretty printer in Python
This article is about a pretty useful built-in module in Python, pprint. The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a well-formatted and more readable way! Let us consider an example: # A python code without pprint import requests def geocode(address): url = "https://maps.googleapis.com/maps/a
2 min read
Pretty-Printing in BeautifulSoup
Prerequisite: requestsBeautifulSoup In this article, we will learn about how to print pretty in BeautifulSoup Using Python. The requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scraping, requests are must be learned for proceeding further with these technologies. When one mak
2 min read
Remove all occurrences of one Linked list in another Linked list
Given two linked lists head1 and head2, the task is to remove all occurrences of head2 in head1 and return the head1. Examples: Input: head1 = 2 -> 3 -> 4 -> 5 -> 3 -> 4, head2 = 3 -> 4Output: 2 -> 5Explanation: After removing all occurrences of 3 -> 4 in head1 output is 2 -> 5. Input: head1 = 3 -> 6 -> 9 -> 8 -
9 min read
When is Doubly Linked List more Efficient than Singly Linked List?
Did you know there are some cases where a Doubly Linked List is more efficient than a Singly Linked List, even though it takes more memory compared to a Singly Linked List? What are those Cases? Well, we will discuss that in the following article, But first, let's talk about Singly and linked lists: What is a Singly Linked List?A singly linked list
4 min read
XOR Linked List - Reverse a Linked List in groups of given size
Given a XOR linked list and an integer K, the task is to reverse every K nodes in the given XOR linked list. Examples: Input: XLL = 7< – > 6 < – > 8 < – > 11 < – > 3, K = 3 Output: 8 < – > 6 < – > 7 < – > 3 < – > 11 Explanation: Reversing first K(= 3) nodes modifies the Linked List to 8 < – > 6
13 min read
XOR Linked List: Remove last node of the Linked List
Given an XOR linked list, the task is to delete the node at the end of the XOR Linked List. Examples: Input: 4<–>7<–>9<–>7Output: 4<–>7<–>9Explanation: Deleting a node from the end modifies the given XOR Linked List to 4<–>7<–>9 Input: 10Output: List is emptyExplanation: After deleting the only node present
15+ min read
XOR Linked List - Pairwise swap elements of a given linked list
Given a XOR linked list, the task is to pairwise swap the elements of the given XOR linked list . Examples: Input: 4 <-> 7 <-> 9 <-> 7Output: 7 <-> 4 <-> 7 <-> 9Explanation:First pair of nodes are swapped to formed the sequence {4, 7} and second pair of nodes are swapped to form the sequence {9, 7}. Input: 1 <
12 min read
Linked List of Linked List
Linked list of linke­d list, also known as nested linke­d lists, is a type of Linked List where each main node stores another full linked list. This structure­ beats old, plain linked lists. It gives way more­ flexibility to store and manage comple­x data. In this article we will learn about the basics of Linked List of Linked List, how to create L
9 min read
Print a singly linked list in spiral order
Given a Linked list, the task is to print a singly linked list in a spiral fashion, starting from the mid and rotating clockwise. If the linked list has even nodes, then you have to choose the left mid. Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> XOutput: 3 -> 4 -> 2 -> 5 -> 1 -> 6 -> XExplanation: Input: 1 -
15+ min read
XOR Linked List - Reversal of a List
Given a XOR linked list, the task is to reverse the XOR linked list. Examples: Input: 4 <–> 7 <–> 9 <–> 7Output: 7 <–> 9 <–> 7 <–> 4Explanation:Reversing the linked list modifies the XOR linked list to 7 <–> 9 <–> 7 <–> 4. Input: 2 <-> 5 <-> 7 <-> 4Output: 4 <-> 7 <-
12 min read
Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read
Python | Queue using Doubly Linked List
A Queue is a collection of objects that are inserted and removed using First in First out Principle(FIFO). Insertion is done at the back(Rear) of the Queue and elements are accessed and deleted from first(Front) location in the queue. Queue Operations:1. enqueue() : Adds element to the back of Queue. 2. dequeue() : Removes and returns the first ele
3 min read
Python | Stack using Doubly Linked List
A stack is a collection of objects that are inserted and removed using Last in First out Principle(LIFO). User can insert elements into the stack, and can only access or remove the recently inserted object on top of the stack. The main advantage of using LinkedList over array for implementing stack is the dynamic allocation of data whereas in the a
4 min read
Python Library for Linked List
Linked list is a simple data structure in programming, which obviously is used to store data and retrieve it accordingly. To make it easier to imagine, it is more like a dynamic array in which data elements are linked via pointers (i.e. the present record points to its next record and the next one points to the record that comes after it, this goes
5 min read
Linked list using dstructure library in Python
Dstructure is a Python library for creating data structures like linked list, stack, queue, hashmap, tree, etc. A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image: pip install dstructure Let's see how to cr
4 min read
Implementation of XOR Linked List in Python
Prerequisite: XOR Linked List An ordinary Doubly Linked List requires space for two address fields to store the addresses of previous and next nodes. A memory-efficient version of Doubly Linked List can be created using only one space for the address field with every node. This memory efficient Doubly Linked List is called XOR Linked List or Memory
6 min read
Random Singly Linked List Generator using Python
In this article, we will learn how to generate a singly linked list using random numbers. Prerequisite: Insertion in Linked List A Singly Linked List is a linear data structure. A linked list is a collection of nodes and in a singly linked list every node contains two things: Data Reference to the next node In this article, we will learn to generat
5 min read
Insert and delete at the beginning in Doubly Linked List in Python
A doubly linked list is a collection of nodes. It is an advanced version of a singly linked list. In a doubly linked list, a node has three elements its data, a link to the next node, and a link to its previous node. In this article, we will learn how to insert a node at the beginning and delete a node from the beginning of the doubly linked list.
6 min read
Singly Linked List in Python
A Singly Linked List is a type of data structure that is made up of nodes that are created using self-referential structures. Each node contains a data element and a reference (link) to the next node in the sequence. This allows for a dynamic and efficient management of data elements. Table of Content What is a Singly Linked List?Representation of
10 min read
Doubly Linked List in Python
Doubly Linked List is a type of linked list in which each node contains a data element and two links pointing to the next and previous node in the sequence. This allows for more efficient operations such as traversals, insertions, and deletions because it can be done in both directions. Table of Content What is a Doubly Linked List?Representation o
13 min read
Circular Linked List in Python
A Circular Linked List is a variation of the standard linked list. In a standard linked list, the last element points to null, indicating the end of the list. However, in a circular linked list, the last element points back to the first element, forming a loop. In this article, we will discuss the circular linked list in Python. Table of Content Wh
13 min read
Python Linked List
In this article, we will learn about the implementation of a linked list in Python. To implement the linked list in Python, we will use classes in Python. Now, we know that a linked list consists of nodes and nodes have two elements i.e. data and a reference to another node. Let's implement the node first.  What is Linked List in PythonA linked lis
13 min read
Print anagrams together in Python using List and Dictionary
Given an array of words, print all anagrams together. Examples: Input: arr = ['cat', 'dog', 'tac', 'god', 'act'] Output: 'cat tac act dog god' This problem has existing solution please refer Anagrams and Given a sequence of words, print all anagrams together links. We will solve this problem in python using List and Dictionary data structures. Appr
2 min read
Print all sublists of a list in Python
Given a list, print all the sublists of a list. Python provides efficient and elegant ways to generate and manipulate sublists. In this article, we will explore different methods how to print all sublists of a given list. Examples: Input: list = [1, 2, 3] Output: [[], [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]Input: [1, 2, 3, 4] Output: [[], [1], [1
3 min read
Python | Remove and print every third from list until it becomes empty
Given a list of numbers, Your task is to remove and print every third number from a list of numbers until the list becomes empty. Examples: Input : [10, 20, 30, 40, 50, 60, 70, 80, 90] Output : 30 60 90 40 80 50 20 70 10 Explanation: The first third element encountered is 30, after 30 we start the count from 40 for the next third element which is 6
4 min read