ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Python] - Generator
    개발/Python 2022. 7. 28. 16:38

    Generator


    Generator functions allow you to declare a function that behaves like an iterator, it can be used in a for loop.
    Generator call like iterator whenever you need

     

    1. yield

    • if use normal function 'return' get value , but Generator use 'yield'
    • yield can be used to control the iteration behaviour of a loop
    • instead of building an array containing all the values and returning them all at once, a generator yields the values one at a time
    # Genrator
    def test_generator() :
        yield 1
        yield 2
        yield 3
    
    test = test_generator()
    
    print(test)
    > <generator object test_generator at 0x000002051CA09A80>
    
    print( next(test) )
    > 1
    print( next(test) )
    > 2
    print( next(test) )
    > 3

    2. why use generator?

    all the values and returning them all at once, so generator have an advantage.

    1. Lazy evaluation(call-by-need)

    • evaluation strategy which delays the evaluation of an expression until its value is needed and which also avoids repeated evaluations

     

    2. memory efficiency

    • Generator use Lazy evaluation, this stargegy Only use memory as needed

    3. Difference List comprehension and generator comprehension

    if num value bigger and bigger so n = 100 , list comprehension result after 100 time but generator result every second.

    import time
    def sleep_func(num) :
        print('sleep')
        time.sleep(1)
    
        return num
    
    # test list_comprehension
    list = [sleep_func(i) for i in range(5)]
    for i in list:
        print(i)
    """
    sleep
    sleep
    sleep
    sleep
    sleep
    0
    1
    2
    3
    4
    """
    
    # test generator_comprehension
    gen = (sleep_func(i) for i in range(5))
    for i in gen:
        print(i)
    """
    sleep
    0
    sleep
    1
    sleep
    2
    sleep
    3
    sleep
    4
    """

     

    3. yield from 

    • if you want list to generator use 'yield from' command.
    def yield_abc():
      for ch in ["A", "B", "C"]:
        yield ch
    
    # right this
    def yield_abc():
      yield from ["A", "B", "C"]

    4. generator comprehension

    • generator comprehesion similar list comprehension. difference is '[]' to '()'.
    gen = (ch for ch in "ABC")
    > <generator object <genexpr> at 0x0000017E292C82E0>

     

    '개발 > Python' 카테고리의 다른 글

    [Python] - Closure  (0) 2022.07.28
    [Python] - First class functions  (0) 2022.07.28
    [Python] - Call by Object reference & Call by sharing  (0) 2022.07.28
    [Python] - Counter  (0) 2022.07.27
    [Python] - Permutation & Combination  (0) 2022.07.27

    댓글

Designed by Tistory.