def double(x):
return x*2
double(3)
6
f = lambda x:2*x
f(3)
6
def add(x,y):
return x+y
add(2,3)
5
f = lambda x,y: x+y
f(2,3)
5
def larger(x,y):
if x>y:
return x
else:
return y
larger(1,10)
10
f= lambda x,y:x if x>y else y
f(1,10)
10
a = [1, 2, 3, 4, 5]
b = [2, 2, 9, 0, 9]
def pick_the_larger(x,y):
result = [] # A list of the largest values
# Assume both lists are the same length
list_length = len(x)
for i in range(list_length):
result.append(max(x[i], y[i]))
return result
pick_the_larger(a,b)
[2, 2, 9, 4, 9]
Very much like what a zipper does, zip takes two equal-length collections and merge them into pairs.
zip(a, b)
<zip at 0x275dce44d08>
map(some_function, some_iterable)
Faster performance: the less helper functions and the more language features
list(map(max, zip(a,b)))
[2, 2, 9, 4, 9]
[max(pair) for pair in zip(a,b)]
[2, 2, 9, 4, 9]
[max(ai,bi) for ai, bi in zip(a,b)]
[2, 2, 9, 4, 9]
# in this case, max works on iterable too
list(map(max,a,b))
[2, 2, 9, 4, 9]
[max(a[x],b[x]) for x in range(len(a))]
[2, 2, 9, 4, 9]