Online Tutorials & Training Materials |
Register Login

Generators Introduction and Example

|| 0

Generators Introduction and Example

What is Generator?

Ans) Generator is function which enables user to declare a function that behaves like an iterator or we can also say generator is a simple way for creating iterators.

How to create Generator in Python?

Please follow the steps below in order create generator in python:

1) If you are defining a remote control object, You can use the yield option to define the channels. This Yield statement is not the same as return statement. In return the function returns the value by eliminating the local variables unlike the yield function.

2) Add itr=remote_control_next(). Itr is a generator which creates an iterator.

3) ‘Next’ is a common property of the iterator. This property is useful if you want the function to return values one by one.

4) Next print the function and For loop works on generators.

5 ) Next, you will produce a Fibonacci sequence using generators.

6) Create a generator function. Define the first two numbers and a while loop.

7.Now create a ‘For’ loop.

8.Run the program to view the output. The sequence will end at 34 as the next number is greater than 50.

9.Next debug using the ‘debug’ option.

10.The debugging process starts

11. Next click on the line next to yield a.

Advantage of Generator

Advantage of using generator over class based iterator are:

  • Generators are better than class based functions as it is not necessary to implement ‘itr’in generators.
  • User does not need to define iter() and next() methods in generators
  • It automatically raises 'StopIteration' therefore there is no need to raise 'StopIteration' exception manually as shown in the image below

Related Articles