In [1]:
def f(x):
    return x**2
In [2]:
f(3)
Out[2]:
9
In [6]:
g = lambda x: x**2
In [7]:
g
Out[7]:
<function __main__.<lambda>>
In [8]:
g(3)
Out[8]:
9
In [9]:
(lambda x: x**2)(3)
Out[9]:
9
In [10]:
(lambda x, y: x**2 + y)(3, 10)
Out[10]:
19
In [11]:
from scipy.integrate import quad
In [12]:
quad(f, 0, 2)
Out[12]:
(2.666666666666667, 2.960594732333751e-14)
In [14]:
quad(lambda x: x**4, 0, 2)
Out[14]:
(6.4, 7.105427357601002e-14)
In [16]:
import math
In [17]:
quad(math.sin, 0, 2)
Out[17]:
(1.4161468365471424, 1.5722388241847156e-14)
In [18]:
quad(lambda x: math.sin(x) * math.cos(x), 0, 2)
Out[18]:
(0.413410905215903, 6.494286172943163e-15)
In [19]:
f(2)
Out[19]:
4
In [21]:
map(f, [0, 1, 3, 4, 5, 100, -3, 42])
Out[21]:
[0, 1, 9, 16, 25, 10000, 9, 1764]
In [23]:
map(lambda x: x**2, [0, 1, 3, 4, 5, 100, -3, 42])
Out[23]:
[0, 1, 9, 16, 25, 10000, 9, 1764]
In [22]:
[f(x) for x in [0, 1, 3, 4, 5, 100, -3, 42]]
Out[22]:
[0, 1, 9, 16, 25, 10000, 9, 1764]
In [24]:
[x**2 for x in [0, 1, 3, 4, 5, 100, -3, 42]]
Out[24]:
[0, 1, 9, 16, 25, 10000, 9, 1764]
In [25]:
def is_positive(n):
    return n > 0
In [27]:
is_positive(1)
Out[27]:
True
In [29]:
filter(is_positive, [1, -2, -3, 4, 10])
Out[29]:
[1, 4, 10]
In [32]:
filter(lambda x: x > 0, [1, -2, -3, 4, 10])
Out[32]:
[1, 4, 10]
In [31]:
[x for x in [1, -2, -3, 4, 10] if x > 0]
Out[31]:
[1, 4, 10]
In [37]:
def f(x, y):
    print("Called with x={} and y={}".format(x, y))
    return x + y
In [38]:
reduce(f, [1, 2, 3, 4], 0)
Called with x=0 and y=1
Called with x=1 and y=2
Called with x=3 and y=3
Called with x=6 and y=4

Out[38]:
10
In [39]:
reduce(f, "test", "X")
Called with x=X and y=t
Called with x=Xt and y=e
Called with x=Xte and y=s
Called with x=Xtes and y=t

Out[39]:
'Xtest'
In [40]:
%loadpy closure_adder42.py
In [47]:
def make_add42():
    def add42(x):
        return x + 42
    return add42


# add42 = make_add42()
# print(add42(2))         # output is '44'
In [60]:
f1 = make_add42()
In [61]:
f2 = make_add42()
In [62]:
id(f1)
Out[62]:
4387378312
In [63]:
id(f2)
Out[63]:
4387378432
In [64]:
f1
Out[64]:
<function __main__.add42>
In [65]:
f2
Out[65]:
<function __main__.add42>
In [66]:
%loadpy closure_adder.py
In [69]:
import math

def make_adder(y):
    def adder(x):
        return x + y
    return adder

add42 = make_adder(42)
addpi = make_adder(math.pi)
# print(add42(2))         # output is 44
# print(addpi(-3))        # output is 0.14159265359
In [70]:
add42(2)
Out[70]:
44
In [71]:
addpi(1)
Out[71]:
4.141592653589793
In []: