Generators in Python
Why do we need a Generator?
Generator is easy to define but it is a little bit difficult to understand,Generator is used for the iterator but in a different way,Generator is nothing but just a simple function.
How to create a generator?
- Generators are normal functions which return an iterator of items instead of a simple object.
- The generators is define by the one or more than one yield statement.
- A generator has a parameter, which we can call and it generates a series of numbers. As a difference with functions, which return a complete array, a generator yields one value at a time as an element of an array and keeps returning each value at a time, consequently acquiring less memory.
- If a function uses at least one ‘yield’ keyword then that function becomes a generator function.
Return Vs Yield statement:
- Yield and returns both return some values.
- The difference is that,
○ Returns: only return a single value and terminate the corresponding function.
○ Yield: It pauses the function and saves all its states and later proceeds with successive calls.
Example: Print Square of first n natural number
def sq_gen(n): number=1 while True: yield number if number==n: return else: number +=1 n= int(input("Enter end of range: ")) sq_arr=[] for i in sq_gen(n): sq_arr.append(i*i) print(sq_arr)
Output:
Python 3.8.4 (tags/v3.8.2:7b3av59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32 >>> ================== RESTART: C:/Users/PC/Desktop/Hello.py ================ Enter end of range: 10 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]