Important Python tips those saves your time


Python is one of the most popular programming languages in the open source space. Look around and you will find it running everywhere, from various configuration tools to XML parsing. To compliment this ‘ten essential Python tips for beginners‘ and ‘ten more essential Python tips‘ features, i’ve compiled yet another collection of ten gems to make your Python experience that much more worthwhile… Any bets on whether we’ll do another?

Converting any charset to UTF-8
You can use the following function to convert any charset to UTF-8.


Removing duplicates from lists
If you want to remove duplicates from a list, just put every element into a dict as a key (for example with ‘none’ as value) and then check dict.keys().

from operator import setitem
def distinct(l):

    d = {}
    map(setitem, (d,)*len(l), l, [])
    return d.keys()

Do-while loops
Since Python has no do-while or do-until loop constructs (yet), you can use the following method to achieve similar results:

while True:
    if condition():

Detecting system platform
To execute platform-specific functions, it is very useful to detect the platform on which the Python interpreter is running. You can use ‘sys.platform’ to find out the current platform.

[Example On Ubuntu Linux]
>>> import sys
>>> sys.platform

[On Mac OS X Snow Leopard]
>>> import sys
>>> sys.platform

Disabling and enabling  garbage collection
Sometimes you may want to enable or disable the garbage collector at runtime. You can use the ‘gc’ module to enable or disable the garbage collection.

>>> import gc
>>> gc.enable
<built-in function enable>
>>> gc.disable
<built-in function disable>

Using C-based modules for better performance
Many Python modules ship with counterpart C modules. Using these C modules will give a significant performance boost in complex applications.

cPickle instead of Pickle, cStringIO instead of StringIO .

Calculating maximum, minimum and sum out of any list or iterable
You can use the following built-in functions.

max: Returns the largest element in the list.
min: Returns the smallest element in the list.
sum: This function returns the sum of all elements in the list. It accepts an optional second argument: the value to start with when summing (defaults to 0).

Representing fractional numbers
Fraction instance can be created using the following constructor:
Fraction([numerator [,denominator]])

Performing math operations
The ‘math’ module provides a plethora of mathematical functions. These work on integer and float numbers, except complex numbers. For complex numbers, a separate module is used, called ‘cmath’.
For example:

math.acos(x): Return arc cosine of x.
math.cos(x): Returns cosine of x.
math.factorial(x) : Returns x factorial.

Working with arrays
The ‘array’ module provides an efficient way to use arrays in your programs. The ‘array’ module defines the following type:

array(typecode [, initializer])

Once you have created an array object, say myarray, you can apply a bunch of methods to it. Here are a few important ones:

myarray.count(x): Returns the number of occurrences of x in a.
myarray.extend(x): Appends x at the end of the array.
myarray.reverse(): Reverse the order of the array.

Passing arguments to a Python script
Python lets you access whatever you have passed to a script while calling it. The ‘command line’ content is stored in the sys.argv list.

import sys
print sys.argv

Loading modules or commands at startup
You can load predefined modules or commands at the startup of any Python script by using the environment variable $PYTHONSTARTUP. You can set environment variable $PYTHONSTARTUP to a file which contains the instructions load necessary modules or commands .

Converting a string to date object
You can use the function ‘DateTime’ to convert a string to a date object.

from DateTime import DateTime
dateobj = DateTime(string)

Converting a list to a string for display
You can convert a list to string in either of the following ways…

1st method:

>>> mylist = [‘spam’, ‘ham’, ‘eggs’]
>>> print ‘, ‘.join(mylist)
spam, ham, eggs

2nd method:

>>> print ‘\n’.join(mylist)

Tab completion in Python interpreter
You can achieve auto completion inside Python interpreter by adding the following lines to your .pythonrc file (or the file you have set Python to read on startup):

import rlcompleter, readline
readline.parse_and_bind(‘tab: complete’)

This will make Python complete partially typed function, method and variable names when you press the Tab key.

Python documentation tool
You can pop up a graphical interface for searching the Python documentation using the command:

$ pydoc -g

You will need python-tk package for this to work.

Python documentation server
You can start an HTTP server on the given port on the local machine. This will give you a nice-looking access to all Python documentation, including third-party module documentation.

$ pydoc -p <portNumber>

Python development software
There are plenty of tools to assist you with Python development. Here are a few important ones:

IDLE: The Python built-in IDE, with autocompletion, function signature popup help, and file editing.
IPython: Another enhanced Python shell with tab-completion and other features.
Eric3: A GUI Python IDE with autocompletion, class browser, built-in shell and debugger.
WingIDE: Commercial Python IDE with free licence available to open-source developers.

Executing functions at the time of Python interpreter termination
You can use ‘atexit’ module to execute functions at the time of Python interpreter termination.

def sum():
def message():
    print(“Executing Now”)
import atexit
Executing Now

Converting from integer to binary, hexadecimal and octal
Python provides easy-to-use functions – bin(), hex() and oct() – to convert from integer to binary, decimal and octal format respectively.

>>> bin(24)
>>> hex(24)
>>> oct(24)


3 thoughts on “Important Python tips those saves your time

  1. Python has to be indented. Or it is not Python.
    I stopped reading at tip 2 – instead of the mumble jambo : “””from operator import setitem
    def distinct(l):
    d = {}
    map(setitem, (d,)*len(l), l, [])
    return d.keys()
    “””” you out in there, just do: ” set(your_list) ” instead. BTW, in an unrelated style flaw, you should never use lower case “l” as a variable name, as it is rather hard to distinguish it, upon reading, from “i|1”, etc…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s