Skip to content
Minsing Log
Go back

English Edition

What is yield? (feat. generators)

Programming & CS

What is yield?

Other functions can return one return value per function, but a yield generator can provide return values multiple times by dividing them up. (Providing them multiple times means that whenever the function is executed, it returns multiple times in the order in which the values were yielded.)

Example code

def yield_abc():
  yield "A"
  yield "B"
  yield "C"
  
for ch in return_abc():
  print(ch)
  
'''
결과 값은
A
B
C
로 나온다.
'''

What is a Generator?

An object that can create multiple pieces of data one at a time as needed, without generating them all in advance.

Why use it?

If multiple return values can be created one at a time as needed, you can obtain the results in portions, which is a huge performance benefit. In terms of memory efficiency, when using the return keyword, all results must be loaded into memory, whereas when using the yield keyword, the results are loaded into memory one at a time.

For this reason, it is often possible to write more efficient programs.

Seems like it would be super useful for coding tests?

Example code Case1)

import time

def return_abc():
  alphabets = []
  for ch in "ABC":
    time.sleep(1)
    alphabets.append(ch)
  return alphabets
for ch in return_abc():
  print(ch)
# 3초 경과
A
B
C

Case2)

import time

def yield_abc():
  for ch in "ABC":
    time.sleep(1)
    yield ch
    
for ch in yield_abc():
  print(ch)
  
'''
# 1초 경과
A
# 1초 경과
B
# 1초 경과
C

'''

References 1. Detailed explanation of generators 2. Detailed explanation of generators

공개 여정 구독

글이 올라오면 이메일로 보내드릴게요.

개발, 창업, 배움, 실패와 회고를 짧고 솔직하게 기록합니다. 검색으로 스쳐가는 독자가 아니라 여정을 따라오는 팬을 만들기 위한 뉴스레터입니다.

뉴스레터는 준비 중입니다. 그동안 RSS 로 구독하거나 이메일 로 알림을 요청해 주세요.


Share this post:

Comments

Sign in with GitHub to leave a comment.


Previous Post
About the sorted() parameter key and lambda values
Next Post
What is __init__.py?