Python – TechEuler

This post was originally published here

Python – TechEulerUnOrdered Linked list – Prepend, Append, Insert At, Reverse, Remove, SearchUse of __slots__ in Python ClassUsage of Underscores before and after function name in Python

Warning: Cannot modify header information – headers already sent by (output started at /home/manikandancsea/public_html/index.php:4) in /home/manikandancsea/public_html/wp-includes/feed-rss2.php on line 8 A Tech blog for nerds Thu, 28 Jul 2016 02:50:56 +0000 en hourly 1 Thu, 28 Jul 2016 02:44:30 +0000

In order to implement an unordered linked list we need to construct linked list which contains Node class, a building block for constructing linked list

Linked List

class Node(object):
    def __init__(self, item): = item = None
    def setNext(self, newnext): = newnext
    def getNext(self):
    def setData(self, item): = item
    def getData(self):

class UnOrderedLinkedList(object):
    def __init__(self):
        self.head = None
        self.tail = None
    def prepend(self, data):
        n = Node(data)
        self.head = n
        if n.getNext() == None:
            self.tail = n
    def append(self, data):
        n = Node(data)
        self.tail = n
    def insertAfter(self, item, data):
        n = Node(data)
        found = False
        current = self.head
        while not found:
            if current.getData() == item:
                found = True
                current = current.getNext()
    def search(self, item):
        found = False
        current = self.head
        while current != None and not found:
            if current.getData() == item:
                found = True
                current = current.getNext()
        return found

    def size(self):
        current = self.head
        size = 0
        while current != None:
            size += 1
            current = current.getNext()
        return size

    def remove(self, item):
        current = self.head
        found = False
        while not found:
            if current.getData() == item:
                found = True
                previous = current
                current = current.getNext()
        if previous == None:
            self.head = current.getNext()

    def printList(self):
        current = self.head
        while current != None:
            print current.getData() , 'n|'
            current = current.getNext()

    def reverse(self):
        current = self.head
        previous = None
        while current:
            next = current.getNext()
            previous = current
            current = next
        self.head = previous
        return self.printList()

]]> 0 Tue, 31 May 2016 17:07:42 +0000


Slots are predominantly used for avoiding dynamically created attributes. It is used to save memory spaces in objects. Instead of dynamically created objects at any time, there is a static structure that does not allow after the initial creation. You would want to use __slots__ if you are going to instantiate a lot (hundreds, thousands) of objects of the same class. __slots__ only exists as a memory optimization tool. This reduces the overhead of the dict of every object that uses slots. Let us see an example with and without using slots:

Python class without __slots__

>>> class A(object):
...     pass
>>> a = A()
>>> a.x = 66
>>> a.y = "dynamically created attribute"

The dictionary containing the attributes of “a” can be accessed like this:

>>> a.__dict__
{'y': 'dynamically created attribute', 'x': 66}

Python class with __slots__

    When we design a class, we can use slots to prevent the dynamic creation of attributes. To define slots, you have to define a list with the name __slots__. The list has to contain all the attributes, you want to use. We demonstrate this in the following class, in which the slots list contains only the name for an attribute “val”.

>>>class S(object):
...    __slots__ = ['val']
...    def __init__(self, v):
...        self.val = v
>>>x = S(42)
>>> = "not possible"

Warning:Unfortunately, there is a downside to using slots. It�™s not great for code maintenance, and it really only saves you when you have thousands of instances. Therefore, don�™t prematurely optimize and use this everywhere!

If you’re using __slots__ under PyPy, Read this on Stackoverflow before you proceed.



]]> 1 Tue, 31 May 2016 15:52:41 +0000

We often find underscore(s) before and after the function name in python while reading the source code. Do you know why and where it has to be used?

I’ll impart the use of underscore in Python’s function name. There are three possibilities of underscore occurred in function name, one underscore at the beginning(_get_name), two underscores at the beginning(__generate), and two underscores at the either side of function(__len__)

One underscore at the beginning:

Python doesn’t have real private methods, so one underline in the start of a method or attribute means you shouldn’t access this method because it not the part of API.

    def _get_errors(self):
        "Returns an ErrorDict for the data provided for the form"
        if self._errors isNone:
        return self._errors

    errors = property(_get_errors)

_get_errors, is “private”, so you shouldn’t access outside the class.

Two underscores in the beginning:

It makes a lot of confusion. It should not be used to create a private method. It should be used to avoid your method to be overridden by a subclass.

class A(object):
    def __test(self):
        print"I'm test method in class A"
    def test(self):

class B(A):
    def __test(self):
        print"I'm test method in class B"
a = A()
print a.test() # Output: I'm test method in class A
b = B()
print b.test()  # Output: I'm test method in class A

As we have seen, b.test() didn’t call B.__test() methods, as we could expect. Basically it is the correct behavior for __. So, when you create a method starting with __ it means that you don’t want anyone to override it, it will be accessible only from inside the class where it was defined.

Two underlines in the beginning and in the end:

When we see a method like __this__, don’t call it. Because it means it’s a method which Python calls, not by you. Let’s take a look:

>>> name ="test string"
>>> name.__len__()
>>> len(name)

>>> number =10
>>> number.__add__(40)
>>> number +50

There is always an operator or native function which calls these magic methods. Sometimes it’s just a hook Python calls in specific situations. For example __init__() is called when the object is created. __new__() is called to build the instance. For more details PEP-8 guide will help more.

]]> 1

Related Posts

Object-Oriented Programming (OOP) in Python 3 In this article you’ll pick up the following basic concepts of OOP in Python: Python Classes Object Instances Defining and Working with Methods ...
8 World-Class Software Companies That Use Python There are over 500 current programming languages, with more being written every day. Admittedly, the majority of these overlap and a large number were...
Modern Web Automation With Python and Selenium In this tutorial you’ll learn advanced Python web automation techniques: Using Selenium with a “headless” browser, exporting the scr...
Shallow vs Deep Copying of Python Objects Assignment statements in Python do not create copies of objects, they only bind names to an object. For immutable objects, that usually doesn’t ...