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

Follow the journey

Get new posts by email.

Short, honest notes on building, startups, learning, failures, and retrospectives, for readers who follow the journey rather than pass through from search.

The newsletter is coming soon. Until then, follow via RSS or email me to get notified.


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?