1.

Where and how is Python keyword yield used?

Answer»

Python’s yield keyword is typically USED along with a generator. A generator is a special type of function that returns an iterator object returning stream of values. APPARENTLY it looks like a normal function , but it doesn’t return a single value. Just as we use return keyword in a function, in a generator yield statement is used.

A normal function, when called, executes all statements in it and returns back to calling environment. The generator is called just like a normal function. However, it pauses on encountering yield keyword, returning the yielded value to calling environment. Because execution of generator is paused, its local VARIABLES and their STATES are saved internally. It resumes when __next__() method of iterator is called. The function finally terminates when __next__() or next() raises StopIteration.

In following example function mygenerator() acts as a generator. It yields one character at a time from the string sequence successively on every call of next()

>>> def mygenerator(string): for ch in string: print ("yielding", ch) yield ch

The generator is called which builds the iterator object

>>> it=mygenerator("Hello World")

Each character from string is pushed in iterator every time next() function is called.

>>> while True: try: print ("yielded character", next(it)) EXCEPT StopIteration: print ("end of iterator") break

Output:

yielding H yielded character H yielding e yielded character e yielding l yielded character l yielding l yielded character l yielding o yielded character o yielding   yielded character   yielding W yielded character W yielding o yielded character o yielding r yielded character r yielding l yielded character l yielding d yielded character d end of iterator

In case of generator, elements are generated dynamically. Since next item is generated only after first is consumed, it is more memory efficient than iterator.



Discussion

No Comment Found