You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
list1= ['a', 'b', 'c', 'd', 'e']
list2= [1, 2, 3, 4, 5]
deff(list1, list2):
""" Uses zip to process 2 lists in parallel. Args: list1: first list. list2: second list. """fori, jinzip(list1, list2):
print(i, j)
print(f.__doc__)
# Uses zip to process 2 lists in parallel.# Args:# list1: first list.# list2: second list.f(list1, list2)
# a 1# b 2# c 3# c 4# e 5
Profiling code snippet performance with timeit
Notice performance increase when list is pre-initialized
importtimeitn=10000000list3= [0]*nlist4= []
print(timeit.timeit('for i in range(0, n): list3[i] = i', number=1, setup='from __main__ import n, list3'))
print(timeit.timeit('for i in range(0, n): list4.append(i)', number=1, setup='from __main__ import n, list4'))
# 0.5378604060970247# 0.8394112652167678
Passing a variable number of function arguments with **kwargs
deff(**kwargs):
# kwargs is a dictifkwargsisnotNone:
forkey, valinsorted(kwargs.items()):
print('%s = %s'%(key, val))
print('----------')
f(a='hello')
f(a='hello', b='world')
f(a='goodbye', b='cruel', c='world')
# a = hello# ----------# a = hello# b = world# ----------# a = goodbye# b = cruel# c = world# ----------
Function passing
# import numeric sine functionfrommathimportsinprint(sin(0))
# simple function for numerical derivative of f at xdefnum_dfdx(f, x, h):
return (f(x+h) -f(x))/float(h)
print(num_dfdx(sin, 0, 0.01))
print(num_dfdx(sin, 0, 0.000001))
# 0.0# 0.9999833334166665# 0.9999999999998334
Anonymous (lambda) functions
Define simple functions in one line of code
# simple function for numerical derivative of f at xdefnum_dfdx(f, x, h):
return (f(x+h) -f(x))/float(h)
num_dfdx(lambdax: x**2, 1, 1e-6)
# 2.0000009999243673magnitude=lambdax: 'small'if1>=x>=-1else'big'print(magnitude(0.5))
# small# map and lamba used often to apply a simple function# to all elements in a listlist(map(lambdax: x**2, range(0,10)))
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]