All categories
    PythonAdvanced

    Generators

    Python generators and iterators: yield values lazily, build memory-efficient sequences, and use next to control iteration.

    01Generator function

    main.py
    def count_up(n):
        for i in range(1, n + 1):
            yield i
    
    for num in count_up(3):
        print(num)
    Output
    1
    2
    3

    02Fibonacci generator

    main.py
    def fib(n):
        a, b = 0, 1
        for _ in range(n):
            yield a
            a, b = b, a + b
    
    print(list(fib(7)))
    Output
    [0, 1, 1, 2, 3, 5, 8]

    03Using next()

    main.py
    def gen():
        yield "a"
        yield "b"
    
    g = gen()
    print(next(g))
    print(next(g))
    Output
    a
    b

    04Take values from an endless generator

    main.py
    def naturals():
        n = 1
        while True:
            yield n
            n += 1
    
    g = naturals()
    print([next(g) for _ in range(5)])
    Output
    [1, 2, 3, 4, 5]