home

Functions

Functions are First Class Citizens

def foo():
    print('foo')

def bar():
    print('bar')

def baz(fun):
    fun()

x = foo
baz(x)
# foo

x = bar
baz(x)
# bar

map()

Used for applying a function to an iterable.

def sqr(x):
    return x**2

nums = range(0, 10)
print(map(sqr, nums))
# <map object at 0x10d38ceb8> : Lazy evaluation!

print(list(map(sqr, nums)))
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

lambda

Used for declaring anonymous functions just in place. Returns a function type.

nums = range(0, 10)
print(list(map(lambda x : x**2, nums)))
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]