This notebook contains all the cool features I found useful or fun!

Mainly from http://stackoverflow.com/questions/101268/hidden-features-of-python?answertab=votes#tab-top

(1) this


In [1]:
import this


The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

(2) antigravity


In [2]:
import antigravity

(3) For ... else


In [3]:
foo = [1, 2, 3]
for i in foo: 
    if i == 0: 
        break 

else: print("i was never 0")


i was never 0

(4) Declare floats using scientific notation


In [4]:
x = 1.4e-3
x


Out[4]:
0.0014

(5) Chaining comparison operators


In [5]:
x = 5
1 < x < 10


Out[5]:
True

(6) Function argument unpacking

You can unpack a list or a dictionary as function arguments using * and **


In [6]:
def draw_point(x, y):
    print x, y

point_foo = (3, 4)
point_bar = {'y': 3, 'x': 2}

draw_point(*point_foo)
draw_point(**point_bar)


3 4
2 3

(7) Enumerate

This is one of the functions I use all the time


In [7]:
a = ['a', 'b', 'c', 'd', 'e']
for index, item in enumerate(a): print index, item


0 a
1 b
2 c
3 d
4 e

(8) Creating generators objects


In [16]:
foo = [1, 2, 3, 4, 5, 6, 7, 8, 9]

def bar(n):
    '''
    return the even number
    '''
    if n%2 == 0:
        return n
    
x = (n for n in foo if bar(n))
for n in x:
    print n


2
4
6
8

In [17]:
#The advantage of this is that you don't need intermediate storage, which you would need if you did
x = [n for n in foo if bar(n)]

In [18]:
#You can append many if statements to the end of the generator, basically replicating nested for loops:
n = ((a,b) for a in range(0,2) for b in range(4,6))
for i in n:
    print i


(0, 4)
(0, 5)
(1, 4)
(1, 5)

(9) If you want to use braces like c instead of whitespace ^)^


In [19]:
from __future__ import braces


  File "<ipython-input-19-2aebb3fc8ecf>", line 1
    from __future__ import braces
SyntaxError: not a chance

(10) Be careful with mutable default arguments


In [26]:
def foo(x=[]):
    x.append(1)
    print x

In [27]:
foo()
foo()
foo()


[1]
[1, 1]
[1, 1, 1]

In [28]:
def foo(x=None):
    if x is None:
        x = []
    x.append(1)
    print x

In [29]:
foo()
foo()
foo()


[1]
[1]
[1]

(11) Close figures in a loop interactively

This is not a hidden feature, but it took me a long time to figure it out


In [10]:
import matplotlib.pyplot as plt
import random

#this dict will save the key your pressed
pressed_key = {}

def press(event):
    print('press', event.key)
    if event.key=='q':
        #close the current figure
        plt.close(event.canvas.figure)
        pressed_key['key'] = event.key

for i in range(10):
    #generate x, y for plotting
    x = random.sample(range(1, 100), 20)
    y = random.sample(range(1, 100), 20)
    
    fig = plt.figure()
    plt.plot(x,y,'o')
    
    fig.canvas.mpl_connect('key_press_event', press)
        
    plt.show() 
        
    #if the pressed key is q, then stop looping through figures
    #note, here must use dict.get('key'), otherwise will have key error
    if pressed_key.get('key') == 'q':
        break


('press', 'q')

(12) Step argument in slice operators


In [2]:
a = [1,2,3,4,5,6,7,8,9,10]
print a[::2]
print a[::-2]


[1, 3, 5, 7, 9]
[10, 8, 6, 4, 2]

(13) In-place value swapping


In [3]:
a = 10
b = 5
print a, b


10 5

In [4]:
a, b = b, a
print a, b


5 10

(14) Dictionaries have a get() method

Dictionaries have a 'get()' method. If you do d['key'] and key isn't there, you get an exception. If you do d.get('key'), you get back None if 'key' isn't there. You can add a second argument to get that item back instead of None, eg: d.get('key', 0).


In [2]:
sum_dict = {}
value = 1
sum_dict[value] = sum_dict.get(value, 0) + 1

In [3]:
sum_dict


Out[3]:
{1: 1}

(15) Conditional assignment


In [5]:
y = 1
x = 3 if (y==1) else 2
x


Out[5]:
3

In [6]:
x = 3 if (y == 1) else 2 if (y == -1) else 1
x


Out[6]:
3

In [ ]:
#Note that you can use if ... else in any expression. For example:
(func1 if y == 1 else func2)(arg1, arg2) 

#or 
x = (class1 if y == 1 else class2)(arg1, arg2)

In [ ]:

(17)


In [ ]:


In [ ]:


In [ ]: