Nifty Python tricks

Hi there folks. It’s been a long time since I last published a post. I have been busy. However in this post I am going to share some really informative tips and tricks which you might not have known about. So without wasting any time lets get straight to them:


Instead of doing:

i = 0 
for item in iterable: 
    print i, item 
    i += 1

We can do:

for i, item in enumerate(iterable):
    print i, item

Enumerate can also take a second argument. Here is an example:

>>> list(enumerate('abc')) 
[(0, 'a'), (1, 'b'), (2, 'c')] 

>>> list(enumerate('abc', 1)) 
[(1, 'a'), (2, 'b'), (3, 'c')]

Dict/Set comprehensions

You might know about list comprehensions but you might not be aware of dict/set comprehensions. They are simple to use and just as effective. Here is an example:

my_dict = {i: i * i for i in xrange(100)} 
my_set = {i * 15 for i in xrange(100)}

# There is only a difference of ':' in both

Forcing float division:

If we divide whole numbers Python gives us the result as a whole number even if the result was a float. In order to circumvent this issue we have to do something like this:

result = 1.0/2

But there is another way to solve this problem which even I wasn’t aware of. You can do:

from __future__ import division 
result = 1/2
# print(result)
# 0.5

Voila! Now you don’t need to append .0 in order to get an accurate answer. Do note that this trick is for Python 2 only. In Python 3 there is no need to do the import as it handles this case by default.

Simple Server

Do you want to quickly and easily share files from a directory? You can simply do:

# Python2
python -m SimpleHTTPServer

# Python 3
python3 -m http.server

This would start up a server.

Evaluating Python expressions

We all know about eval but do we all know about literal_eval? Perhaps not. You can do:

import ast 
my_list = ast.literal_eval(expr)

Instead of:

expr = "[1, 2, 3]" 
my_list = eval(expr)

I am sure that it’s something new for most of us but it has been a part of Python for a long time.

Profiling a script

You can easily profile a script by running it like this:

python -m cProfile

Object introspection

You can inspect objects in Python by using dir(). Here is a simple example:

>>> foo = [1, 2, 3, 4]
>>> dir(foo) 
['__add__', '__class__', '__contains__', 
'__delattr__', '__delitem__', '__delslice__', ... , 
'extend', 'index', 'insert', 'pop', 'remove', 
'reverse', 'sort']

Debugging scripts

You can easily set breakpoints in your script using the pdb module. Here is an example:

import pdb

You can write pdb.set_trace() anywhere in your script and it will set a breakpoint there. Super convenient. You should also read more about pdb as it has a couple of other hidden gems as well.

Simplify if constructs 

If you have to check for several values you can easily do:

if n in [1,4,5,6]:

instead of:

if n==1 or n==4 or n==5 or n==6:

Reversing a list/string

You can quickly reverse a list by using:

>>> a = [1,2,3,4]
>>> a[::-1]
[4, 3, 2, 1]

# This creates a new reversed list. 
# If you want to reverse a list in place you can do:


and the same can be applied to a string as well:

>>> foo = "yasoob"
>>> foo[::-1]

Pretty print

You can print dicts and lists in a beautiful way by doing:

from pprint import pprint 

This is more effective on dicts. Moreover, if you want to pretty print json quickly from a file then you can simply do:

cat file.json | python -m

Ternary Operators

Ternary operators are shortcut for an if-else statement, and are also known as a conditional operators. Here are some examples which you can use to make your code compact and more beautiful.

[on_true] if [expression] else [on_false]
x, y = 50, 25
small = x if x < y else y

Thats all for today! I hope you enjoyed this article and picked up a trick or two along the way. See you in the next article. Make sure that you follow us on Facebook and Twitter!

Do you have any comments or suggestions? You can write a comment or email me on yasoob.khld (at)

17 thoughts on “Nifty Python tricks”

  1. >>> a = [1,2,3,4]
    >>> a[::-1]
    It does not reverse the list, it creates a new list which is reversed. The ‘list’ class has a reverse() method for that purpose.
    (but if ‘a’ is a string — strings are immutable — the a[::-1] way is quite good)

  2. Curious that you’re mentioning ast.literal_eval without any reason. It’s actually a much more limited eval and is not designed to evaluate general Python. The ast module is for modeling Python’s syntax. Try a few statements with literal_eval; you will not get far.

    1. The limits ARE the feature: We use lit.eval all the time for *secure* (de)serializiation of structures into strings and back. The reason we prefer compared to json is this:
      >>> ‘é’ in json.loads(json.dumps([‘é’]))
      >>> ‘é’ in literal_eval(str([‘é’]))

  3. I think we should use `{1,4,5,6}` instead of `[1,4,5,6]` for `in` operator because `set` can access each element by O(1).

  4. On simple if/else statements like shown under Ternary Operators, I like to use indexing where the test returns 0 (False) or 1 (True). So you could represent as: small = (y,x)[x<y]

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