Who can help me to understand the next code about yield? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Who can help me to understand the next code about yield?

def make_word(): word="" for ch in "spam": word+=ch yield word print(list(make_word))

5th Apr 2017, 9:57 AM
Simon
4 Answers
+ 3
Output is ['s', 'sp', 'spa', 'spam'], if you fix the syntax. If you iterate over a string, you get it char by char. These chars are appended to word, which is yielded.
5th Apr 2017, 11:26 AM
Tob
Tob - avatar
0
I don‘t understand the output -['spam', 'spam', 'spam', 'spam'], how the itera runs?
5th Apr 2017, 9:59 AM
Simon
0
see my sample of using a generator. it helps to understand yield statement. https://code.sololearn.com/coG53x8M5n8U/?ref=app
5th Apr 2017, 12:42 PM
Андрей
0
Your code just works fine! I have tried printing with an additional parentheses for make_word as make_word(). #print(list(make_word())) def make_word(): word="" for ch in "spam": word+=ch yield word print(list(make_word()))
12th Apr 2017, 11:37 AM
subash m
subash m - avatar