generators and yield keyword..

Home Forums Python Programming generators and yield keyword..

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #2154 Reply
    Humble
    Keymaster

    Hmmm… Like iterators, there is one more called generators.. looks almost same with respect to the protocol implementation.. Any way what are those ? I would call generator as a constructor.. it can construct ‘result’ on fly .. That said, instead of giving a resulting list with entire elements in one shot, it gives us a ‘generator’ variable on which you can iterate over and construct the resulted elements..

    Python return a ‘generator’ as soon as it notice a “yield” keyword. May be you would have noticed, “yield” keyword inside a function instead of “return”.. As soon as you returned from a function the local variables inside the function are lost.. how-ever in case of “yield” key word, the next execution starts from the state where it was left off.

    When/how generators are useful? well, suppose you have a big list of elements as a return, it will occupy the memory for its storing.. instead of that , isnt it good if you store a variable like thing and iterate over it on demand? yes, thats the advantage of generators..

    The common rule to put the yield statement is , it should be put into a place where the generator returns an intermediate result to the caller and sleeps until the next invocation occurs.

    As like iterator protocol, you can get next element of the result by calling next() method on generator.

    One good example of making use of generators would be ‘factorial’ implementation.

Viewing 1 post (of 1 total)
Reply To: generators and yield keyword..
Your information: