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))
4 odpowiedzi
+ 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.
0
I don‘t understand the output -['spam', 'spam', 'spam', 'spam'], how the itera runs?
0
see my sample of using a generator. it helps to understand yield statement.
https://code.sololearn.com/coG53x8M5n8U/?ref=app
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()))