How To Use Python Generator And Yield Example

Sometimes, the number of elements in a sequence or collection is very large. If all elements are created and put into memory, the pressure on the computer is very large. For example, suppose you need to get a data set of 10 ** 20 size, which is so huge, generate every number and put it in a memory list is a crude way. Is there such a large memory?

If the elements can be calculated according to some algorithm to make the subsequent elements can be calculated continuously in the process of circulation without creating a complete set of elements, thus can save a lot of spaces. In python, this mechanism of calculating elements while looping is called generator.

1. Create Python Generator Use Generator Comprehension.

Below is an example about how to create python generator. You can create generator comprehension with parentheses.

# Create python generator object.

>>> gen = (x + x for x in range(1, 6))
>>> 
>>> type(gen)
<class 'generator'>
>>> 
>>> gen
<generator object <genexpr> at 0x10faeaed0>

Much like an iterator, the next return value of the generator can be obtained through the next() function.

>>> gen = (x + x for x in range(1, 6))

>>> next(gen)
2
>>> next(gen)
4
>>> next(gen)
6
>>> next(gen)
8
>>> next(gen)
10
>>> next(gen)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

We can also use for loop to get each element in the generator.

>>> gen = (x + x for x in range(1, 6))
>>> 
>>> for x in gen:
...     print(x)
... 
2
4
6
8
10

2. Create Python Generator Use Yield Keyword In Python Function.

In python, a function which use yield keyword in the function body will become a generator. In the process of calling the generator function, the function will pause and save all current running information every time it encounters yield keyword, and return the value of yield keyword decorated variable or expression, and continue to run from the current location when you execute the next() method on the generator object.

>>> def test_func(n): 
...     for i in range(n):
...             yield i**2
... 
>>> gen = test_func(10)
>>> 
>>> type(gen)
<class 'generator'>
>>> 
>>> for x in gen:
...     print(x, end=" ")
... 
0 1 4 9 16 25 36 49 64 81 >>>

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.