Generators: =========== What are generators? ===================== ==> generators are functions in python ==> used to generate/create iterators ==> iterators can perform traversing on list/tuple etc. ==> return a traversal object. helps to traverse all the elements/items one at a time present in the iterator. ==> The difference between the normal function and generator function is: 1) the normal function can use "return" statement to return a value. def normal_function(): return 10,20,30,40 t1,t2,t3,t4 = normal_function() print(t1,t2,t3,t4) 2) the generator function can use "yield" statement to return values. def gen_fun(): yield 10 yield 20 yield 30 for i in gen_fun(): print(i) ================================== return Vs yield: ================ 1) yield is the keyword, we can use in generator function. return is the keyword, we can use in normal function. 2) yield is responsible for controlling the flow of the generator function. After returning the value using "yield", it pauses the execution by saving the states. Whereas, the return statement returns the values and terminates the function. ===================================================== Difference between Generator function and normal function: ========================================================== next(): ====== an inbuilt function which can helps to understand whether the generator function is pause the implementation while returning the value. def sequence(x): for i in range(x): yield i range_values = sequence(10) print(next(range_values)) print(next(range_values)) print(next(range_values)) print(next(range_values)) print(next(range_values)) print(next(range_values)) print(next(range_values)) print(next(range_values)) print(next(range_values)) print(next(range_values)) # print(next(range_values)) ======================================= Defining the generator function using generator expression: ============================================================ lambda function ==> anonymous function p = 7 genr = (i for i in range(p) if i % 2 == 0) # generator object list_values = [i for i in range(p) if i % 2 == 0] # list variable print(genr) # we can't access the generator object directly. print(list_values) for k in genr: print(k) ================================================= Uses of Generators: =================== 1) Easy to Implement 2) Memory Efficient 3) Infinite Sequence