def reverse(data): for index in range(len(data)-1, -1, -1): # repeat as many as the length of data, # decrement -1 each time till the index becomes -1 #since index starts with 0 yield data[index] for char in reverse('gold'): print(char)
Generators are a simple and powerful tool for creating iterators. They are written like regular functions but use the yield statement whenever they want to return data. Each time next() is called on it, the generator resumes where it left off (it remembers all the data values and which statement was last executed). An example shows that generators can be trivially easy to create.
Anything that can be done with generators can also be done with class-based iterators as described in the previous section. What makes generators so compact is that the __iter__() and __next__() methods are created automatically.
Another key feature is that the local variables and execution state are automatically saved between calls. This made the function easier to write and much more clear than an approach using instance variable like self.index and self.data
In addition to automatic method creation and saving program state, when generators terminate, they automatically raise StopIteration. In combination, these features make it easy to create iterators with no more effort than writing a regular function.
9.10. Generator Expressions
Some simple generators can be coded succinctly as expressions using a syntax similar to list comprehensions but when parantheses instead of square brackets. These expressions are designed for situations where the generator in used right away by an enclosing function. Generator Expressions are more compact but less versatile than full generator definitions and tend to be more memory friendly than equivalent list comprehensions.
#the sum() adds the items of an ITERABLE and returns the sum(it is numeric data typed.)
# print(sum(i*i for i in range(10))) # print(type(sum(i*i for i in range(10))))# previous line returns int xvec = [10, 20, 30] yvec = [7, 5, 3] print(sum(x*y for x,y in zip(xvec, yvec)))
댓글
댓글 쓰기