It is an anonymous function which can be used as a parameter function with sorted/sort,bisect,map,filter,reduce
>> lambda x: x*2;
>> lambda (x,y) : x+y
It is used to perform some operations on all items of sequence in one line and get a map object is iterable and can be converted to sequence
>> ls = [1,2,3,4,5,6,7]
>> sqrls = map( lambda x: x**2, ls )
<map object at 0x7f8848ff3048>
>> list(sqrls)
[1, 4, 9, 16, 25, 36, 49]<br>
It is used to filter some items from a sequence to form a new sequence
>> ls = [1,4,6,7,9,11,15,16,17,19,21]
>> mod3 = filter(lambda x: x%3==0, ls )
>> mod3
<filter object at 0x7f5d424fd588>
>> mod3 = list(mod3)
>> mod3
[6, 9, 15, 21]
It is used to get a single value result from a whole sequence
>> ls = [1,4,6,7,9,11,15,16,17,19,21]
>> from functools import reduce
>> no = reduce(lambda x,y : x+y, ls)
>> no
126
It combines n list of equal sizes and form a iterable of same size containing n sized tuples
>> questions = ['name', 'quest', 'favorite color']
>> answers = ['lancelot', 'the holy grail', 'blue']
>> for q, a in zip(questions, answers):
... print('What is your {0}? It is {1}.'.format(q, a))
It is a queue that keep the elements sorted
>> from queue import PriorityQueue
>> q = PriorityQueue()
>> ls = [ (34,'b'), (41,'d'), (11,'a'), (34,'c'), (36,'e') ]
>> for i in range(5):
... q.put(ls[i]) # sort by first element than second, only true for integers
>> q.queue
[(11, 'a'), (34, 'c'), (34, 'b'), (41, 'd'), (36, 'e')]
>> len(q.queue)
5
>> q.get() #pop first element
(11, 'a')
Function that returns an object(iterator) which can be iterated over, we can create it by using yield statement. Methods like __iter__()
and __next__()
are implemented automatically. We can use next().
>>> def my_gen():
... i=0
... while True:
... yield i
... i+=1
>>> a = my_gen()
>>> for i in range(5):
... print(next(a))
0
1
2
3
4
* Using Joblib :
```
>> from joblib import Parallel, delayed
>> import requests
>> def getImage(index, link ):
...response = requests.get(link, stream=True)
...with open(f"images/{index}.jpg", 'wb') as f:
......for data in response:
.........f.write(data)
>> Parallel(n_jobs=-2, prefer="threads")(delayed(getImage)(index, link) for index, link in index_link)
```
It takes some function and add some more functionality to it and return it. Decorators acts as a wrapper to that function.
>>> def smart_divide(func):
... def inner(a,b):
... print("We are dividing",a,"&",b)
... if b==0:
... print("Whoops!!")
... return
... return func(a,b)
... return inner
>>> @smart_divide
... def divide(a,b):
... return a/b
>>> divide(6,2)
We are dividing 6 & 2
3.0
>>> divide(6,0)
We are dividing 6 & 0
Whoops!!
Operator Overloading, Callable object, iterable object, property decorator, method overloading
class Person:
def __init__(self,name="xyz",marks=0,dob="0/0/0",sub_marks=[]):
#constructor
self.name=name
self.marks=marks
self.dob=dob
self.sub_marks = sub_marks
self.index = 0
def __int__(self):
#implement int() method, | __str__ "str()", __long__ "long()", __float__ "float()", __hex__ "hex()"
return self.marks
def __repr__(self):
#represent object as string
return f"Name:{self.name}, Marks:{self.marks}, Date of Birth:{self.dob}"
def __add__(self,person):
#operator overloading "+", | __mul__ "*", __sub__ "-", __mod__ "%", __pow__ "**", __floordiv__ "//"
return Person(self.name+' and '+person.name,self.marks+person.marks)
def __ge__(self,person):
#operator overloading ">=", | __lt__ "<", __le__ "<=", __eq__ "=", __ne__ "!="
return self.marks >= person.marks
def __eq__(self,person):
#operator overloading "==", | __ne__ "!="
return self.marks == person.marks
def __and__(self, person):
#operator overloading "&", | __xor__ "^", __or__ "|"
return self.ispassed & person.ispassed
def __pos__(self):
#urinary operator "+", | __neg__ "-", __abs__ "abs()", __invert__ "~"
if self.marks <= 33: return "D"
elif self.marks > 75: return "A"
elif self.marks > 50: return "B"
else: return "C"
def __totalsub(self):
#private function
return len(self.sub_marks)
@property
def ispassed(self):
#@property decorator is built in attribute to give property using function
return self.marks > 33
def __bool__(self):
#builtin bool() method to return True or False. can be used in if, while etc
return self.ispassed
def __call__(self,new_marks):
#__call__ method can be used to turn the instances of the class into callables
self.sub_marks.append(new_marks)
def __getitem__(self, index):
#behave class as a list
return self.sub_marks[index]
def __len__(self):
#implement len() attr of class
return len(self.sub_marks)
@staticmethod
def about():
#can be called without object
return "student class"
>> person1 = Person("John Doe",43,'2001/02/11',sub_marks=[10,3,5,8,4,5,8])
>> person2 = Person("Paul Woe",21,'1995/01/22')
>> person1, person2
(Name:John Doe, Marks:43, Date of Birth:2001/02/11,
Name:Paul Woe, Marks:21, Date of Birth:1995/01/22)
>> person1+person2
Name:John Doe and Paul Woe, Marks:64, Date of Birth:0/0/0
>> person1 & person2, person1.ispassed, person2.ispassed, bool(person1),bool(person2), person1==person2
(False, True, False, True, False, False)
>> for m in person1:
... print(m, end=" ")
10 3 5 8 4 5 8
>> person1(11)
>> print(list(person1))
[10, 3, 5, 8, 4, 5, 8, 11]
>> sum(person1),len(person1), person1[4],person1[1]
(54, 8, 4, 3)
>> +person1
'C'
>> Person.about()
'student class'