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 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 under 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, bellow 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]
[10, 15, 20]
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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.