[Generator] yield, yield from

2021. 8. 24. 16:02

yield와 yield from을 활용해서 기존의 코드를 굉장히 깔끔하게 리팩토링한 파이썬 코드를 찾았다.

 

Solution 3 - https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/1420711/C%2B%2BJavaPython-3-solutions%3A-HashSet-Stack-Python-yield-Solutions-O(H)-space 

 

 

 

yield는 generator를 만들어주는 코드임을 알고 있었는데, yield from은 처음봄

간단히 말해서, 다른 generator로부터 값을 뽑아내는 기능 (coroutine 만드는데 유용?)

# 원래 코드
def func(an_iterable):
    for item in an_iterable:
        yield item

# 줄여서        
def func(an_iterable):
    yield from an_iterable

 

Related question

 

https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do

+ Recent posts