Enumeration

Previously we did it like this:

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

Now we do it like this:

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

The enumerate function can also accept a second parameter, like this:

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

Dictionary/Set Comprehension

You may know how to do list comprehension, but perhaps not dictionary/set comprehension. They are simple, easy to use, and efficient. Like the example below:

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 floating-point division

If we divide an integer, even if the result is a float, Python 2 (editor's note: I added the version number here) will still give us an integer. To avoid this problem, we need to do this:

result = 1.0/2

But now there is another way to solve this problem, and I didn't even realize such a method existed before. You can do the following:

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

See, now you don't need to append ".0" to the data to get the exact answer. Note that this trick only works in Python 2. In Python 3, you don't need to perform the import, because it is already imported by default.

Simple server

Do you want to quickly and conveniently share files in a directory? You can do it like this:

# Python2
python -m SimpleHTTPServer

# Python 3
python3 -m http.server

This will start a server.

Evaluating Python expressions

We all know the eval function, but do we know the literal_eval function? Maybe many people don't. You can use this operation:

import ast 
my_list = ast.literal_eval(expr)

to replace the following operation:

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

I believe this form is seen for the first time by most people, but in fact it has already existed in Python for a long time.

Script profiling

You can easily profile scripts by running the following code:

python -m cProfile my_script.py

Object introspection

In Python, you can inspect objects with the dir() function. Like the example below:

>>> 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 via the pdb module. Like the example below:

import pdb
pdb.set_trace()

You can add pdb.set_trace() anywhere in your script, and this function will set a breakpoint at that position.

Simplifying if statements

If you need to check several values, you can use the following method:

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

to replace the following way:

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

Reversing strings/sequences

You can quickly reverse a sequence with the following method:

>>> 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:
 
a.reverse()

This method also works for reversing strings:

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

Pretty printing

You can pretty print dictionaries and sequences in the following way:

from pprint import pprint 
pprint(my_dict)

This way is more efficient for printing dictionaries. In addition, if you want to pretty print a JSON document from a file, you can use the following method:

cat file.json | python -m json.tool

Ternary operator

The ternary operator is a shortcut for if-else statements, also known as conditional expressions. Here are a few examples for your reference; they can make your code more compact and more elegant.

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