Some Python Useful Ways

This Blog tracsfer from (here)[https://pythontips.com/2015/04/19/nifty-python-tricks/]

Enumerate

Instead of doing:

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

We can do:

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

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

1
2
3
4
5
>>> 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:

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

Forcing float divsion:

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:

1
result  = 1.0 / 2

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

1
2
3
from __futhure__ import division

result = 1/2

Now you don’t need to append .0 in order to get an accurate answer.

Do note that this trick is for Pyhton 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 simple do:

1
2
3
4
5
# python 2
python -m SimpleHTTPServer localhost:8080

# python 3
python3 -m http.server localhost:8080

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:

1
2
3
import ast

my_list = ast.literal_eval(expr)

Instead of:

1
2
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 runnung it like this:

1
python -m cProfile my_script.py

Object introspection

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

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

Debugging script

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

1
2
3
import pdb

pdb.set_trace()

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 welll.

Simplify if constructs

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

1
if n in [1,2,3,4]:

instead of:

1
if n == 1 or n == 2 or n == 3:

Reversing a list/string

You can quickly reverse a list by using:

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

a.reverse()

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

1
2
3
>>> foo = 'abcd'
>>> foo[::-1]
'dcba'

Pretty print

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

1
2
form pprint import pprint
pprint(my_dict)

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

1
cat file.json | python -m json.tools

Ternary Operators

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

1
2
3
[on_true] if [expression] else [on_false]
x, y = 50, 25
samle = x if s < y else y