Mainly from http://stackoverflow.com/questions/101268/hidden-features-of-python?answertab=votes#tab-top
In [1]:
import this
In [2]:
import antigravity
In [3]:
foo = [1, 2, 3]
for i in foo:
if i == 0:
break
else: print("i was never 0")
In [4]:
x = 1.4e-3
x
Out[4]:
In [5]:
x = 5
1 < x < 10
Out[5]:
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)
In [7]:
a = ['a', 'b', 'c', 'd', 'e']
for index, item in enumerate(a): print index, item
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
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
In [19]:
from __future__ import braces
In [26]:
def foo(x=[]):
x.append(1)
print x
In [27]:
foo()
foo()
foo()
In [28]:
def foo(x=None):
if x is None:
x = []
x.append(1)
print x
In [29]:
foo()
foo()
foo()
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
In [2]:
a = [1,2,3,4,5,6,7,8,9,10]
print a[::2]
print a[::-2]
In [3]:
a = 10
b = 5
print a, b
In [4]:
a, b = b, a
print a, b
In [2]:
sum_dict = {}
value = 1
sum_dict[value] = sum_dict.get(value, 0) + 1
In [3]:
sum_dict
Out[3]:
In [5]:
y = 1
x = 3 if (y==1) else 2
x
Out[5]:
In [6]:
x = 3 if (y == 1) else 2 if (y == -1) else 1
x
Out[6]:
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 [ ]:
In [ ]:
In [ ]:
In [ ]: