Hướng dẫn python generator geeksforgeeks

View Discussion

Show

    Improve Article

    Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Prerequisites: Yield Keyword and Iterators There are two terms involved when we discuss generators.

    Generator-Function: A generator-function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function. 

    Python3

    def simpleGeneratorFun():

        yield 1           

        yield 2           

        yield 3           

    for value in simpleGeneratorFun():

        print(value)

    Generator-Object : Generator functions return a generator object. Generator objects are used either by calling the next method on the generator object or using the generator object in a “for in” loop (as shown in the above program). 

    Python3

    def simpleGeneratorFun():

        yield 1

        yield 2

        yield 3

    x = simpleGeneratorFun()

    print(next(x))

    print(next(x))

    print(next(x))

    So a generator function returns an generator object that is iterable, i.e., can be used as an Iterators . As another example, below is a generator for Fibonacci Numbers. 

    Python3

    def fib(limit):

        a, b = 0, 1

        while a < limit:

            yield a

            a, b = b, a + b

    x = fib(5)

    print(next(x))

    print(next(x))

    print(next(x))

    print(next(x))

    print(next(x))

    print("\nUsing for in loop")

    for i in fib(5):

        print(i)

    Output

    0
    1
    1
    2
    3
    
    Using for in loop
    0
    1
    1
    2
    3
    

    Applications: 

    Suppose we create a stream of Fibonacci numbers, adopting the generator approach makes it trivial; we just have to call next(x) to get the next Fibonacci number without bothering about where or when the stream of numbers ends. A more practical type of stream processing is handling large data files such as log files. Generators provide a space-efficient method for such data processing as only parts of the file are handled at one given point in time. We can also use Iterators for these purposes, but Generator provides a quick way (We don’t need to write __next__ and __iter__ methods here).

    This article is contributed by Shwetanshu Rohatgi. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.


    View Discussion

    Improve Article

    Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    In Python, to create iterators, we can use both regular functions and generators. Generators are written just like a normal function but we use yield() instead of return() for returning a result. It is more powerful as a tool to implement iterators. It is easy and more convenient to implement because it offers the evaluation of elements on demand. Unlike regular functions which on encountering a return statement terminates entirely, generators use a yield statement in which the state of the function is saved from the last call and can be picked up or resumed the next time we call a generator function. Another great advantage of the generator over a list is that it takes much less memory. 

    In addition to that, two more functions _next_() and _iter_() make the generator function more compact and reliable. Example : 

    Python3

    def generator():

        t = 1

        print ('First result is ',t)

        yield t

        t += 1

        print ('Second result is ',t)

        yield t

        t += 1

        print('Third result is ',t)

        yield t

    call = generator()

    next(call)

    next(call)

    next(call)

    Output : 

    First result is  1
    Second result is  2
    Third result is  3

    Difference between Generator function and Normal function – 

    • Once the function yields, the function is paused and the control is transferred to the caller.
    • When the function terminates, StopIteration is raised automatically on further calls.
    • Local variables and their states are remembered between successive calls.
    • The generator function contains one or more yield statements instead of a return statement.
    • As the methods like _next_() and _iter_() are implemented automatically, we can iterate through the items using next().

    There are various other expressions that can be simply coded similar to list comprehensions but instead of brackets we use parenthesis. These expressions are designed for situations where the generator is used right away by an enclosing function. Generator expression allows creating a generator without a yield keyword. However, it doesn’t share the whole power of the generator created with a yield function. Example :  

    Python3

    generator = (num ** 2 for num in range(10))

    for num in generator:

        print(num)

    Output : 

    0
    1
    4
    9
    16
    25
    36
    49
    64
    81

    We can also generate a list using generator expressions : 

    Python3

    string = 'geek'

    li = list(string[i] for i in range(len(string)-1, -1, -1))

    print(li)

    Output: 

    ['k', 'e', 'e', 'g']

    This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.
    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.