Lambda expressions allow us to create "anonymous" functions i.e functions without a name. This basically means we can quickly make ad-hoc functions without needing to properly define a function using def.
Function objects returned by running lambda expressions work exactly the same as those created and assigned by defs.
However the following are the key differences between lambda functions and 'def' functions.
In [2]:
# Normal function
def square(num):
result = num**2
return result
square(2)
Out[2]:
In [3]:
# Simplified Version #1
def square(num):
return num**2
square(3)
Out[3]:
In [4]:
# Simplified Version #1
def square(num):return num**2
square(4)
Out[4]:
The syntax for lambda function is quite simple.
lambda argument_list:expression
The argument list consists of a comma separated list of arguments and the expression is an arithmetic expression using these arguments.
The following example returns the square of a given number.
In [5]:
square = lambda num: num **2
square(5)
Out[5]:
In [7]:
sum1 = lambda x,y: x+y
print(sum1(3,4))
even = lambda x: x%2==0
print(even(12))
first = lambda str: str[0]
print(first('Hello'))
rev = lambda str:str[::-1]
print(rev('Hello'))
The function filter(function,list) offers an elegant way to filter out all the elements of a list, for which the function function returns True.
The function filter(f,1) needs a function f as its first argument. f returns a Boolean value i.e. either True or False. This function will be applied to every element of the list l. Only if f returns True will the element of the list included in the resultset.
In [13]:
nums = [2,3,4,7,9,10]
evens = list(filter(lambda x: x%2==0,nums))
print(evens)
map is a function with 2 arguments.
result = map(function,seq)
The first argument func is the name of a function and the second a sequence (e.g. a list) seq. map() applies the function func to all the elements of the sequence seq.
It returns a new list with all the elements changed by func.
In [22]:
def far(T):
return ((float(9)/5)* T + 32)
def cel(T):
return (float(5)/9) * (T - 32)
temp = (0,35,90,125)
F = map(far,temp)
temp1 = list(F)
C = map(cel,temp1)
print(temp1)
print(list(C))
In [26]:
temp = (0,35,90,125)
f = map(lambda x: (float(9)/5)*x +32,temp)
f_list = list(f)
c = map(lambda x: (float(5)/9) * (x -32),f_list)
print(f_list)
print(list(c))
map() can also be applied to more than one list but the lists must have the same length. map() will apply its lambda function to the elements of the argument lists, i.e. it first applies to the elements with the 0th index, then to the elements with the 1st index until the n-th index is reached:
In [30]:
a = [1,2,3,4]
b = [5,6,7,8]
c = [-1,-2,1,2]
list(map(lambda x,y,z:x+y-z,a,b,c))
Out[30]:
reduce(func,seq)
If seq = [s1,s2,s3,...,sn], calling reduce(func,seq) works like this:
In [34]:
from functools import reduce
reduce(lambda x,y: x+y, [47,23,11,34])
Out[34]:
In [35]:
from functools import reduce
reduce(lambda x,y: x if (x > y) else y, [47,12,33,95])
Out[35]:
In [39]:
from functools import reduce
reduce(lambda x,y: x * y, range(1,10,2))
Out[39]:
In [41]:
a = [1,2,3]
b = [4,5,6]
list(zip(a,b))
Out[41]:
zip() should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables. Only the shortest iterable itme will be taken and any extra elements will be ignored
In [42]:
# Example - 1
x = [1,2,3]
y = [4,5]
list(zip(x,y))
Out[42]:
In [43]:
# Example - 2
a = ['a','b']
b = ['c','d','e']
list(zip(a,b))
Out[43]:
In [47]:
d1 = {'a':1,'b':2}
d2 = {'c':3,'c':4}
print(list(zip(d1,d2)))
This makes sense because simply iterating through the dictionaries will result in just the keys. We would have to call methods to mix keys and values
In [50]:
def swapdic(d1,d2):
dout = {}
for d1key,d2val in zip(d1,d2.values()):
dout[d1key] = d2val
return dout
swapdic(d1,d2)
Out[50]:
In [53]:
colors = ['Blue','Black','White','Red']
list(enumerate(colors))
Out[53]:
In [54]:
list(enumerate(colors,1))
Out[54]:
In [56]:
for index,item in enumerate(colors):
print(index)
print(item)
In [57]:
for i,j in enumerate(colors):
if i == 2:
break
print(j)
In [58]:
lst = [True, True, False, True]
all(lst)
Out[58]:
In [59]:
any(lst)
Out[59]:
In [1]:
complex() # if no arguments are given results in 0j
Out[1]:
In [4]:
complex(2,4)
Out[4]:
In [2]:
complex('2') # if imag part is omitted substitutes with 0j
Out[2]:
In [5]:
complex('2','3') # this will create an error as the second parameter cannot be a string.
In [3]:
complex('1+2j')
Out[3]:
In [8]:
complex('3',2) # cannot take a secord argument if first is a strink