Open In App

Pretty print Linked List in Python

Last Updated : 26 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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
Python Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list. For example, if first list is 5->7->17->13->11 and second is 12->10->2->4->6, the first list should become 5->12->7->10->17->2->13->4->11->6 and second list should become empty. The
3 min read
Generate Linked List consisting of maximum difference of squares of pairs of nodes from given Linked List
Given a Linked List of even number of nodes, the task is to generate a new Linked List such that it contains the maximum difference of squares of node values in decreasing order by including each node in a single pair. Examples: Input: 1 -> 6 -> 4 -> 3 -> 5 ->2Output: 35 -> 21 -> 7Explanation:The difference between squares of 6
11 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