in Python, yield function with List is confusing | Sololearn: Learn to code for FREE!
0

# in Python, yield function with List is confusing

Here I try to print in two different ways, one is with list, and another one is with for loop. However, the result of using for loop make sense, but using list is different from what I'd have thought. Can you help me explain the reason? And in what situation you might use List function instead of for loop? Thank you! def my_gen(): n = 1 print('This is printed first') yield n n += 1 print('This is printed second') yield n n += 1 print('This is printed at last') yield n print (list(my_gen())) # Using for loop below, and this make sense for item in my_gen(): print(item)

25th Aug 2018, 2:31 PM
Vosen Chen
5 Antworten
+ 6
All the list() function does is it converts whatever iterable it gets to a list, and returns it. >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list((3, 5, 8, 13)) [3, 5, 8, 13] >>> list('abcd') ['a', 'b', 'c', 'd'] ----------------------- If you use a simpler generator or a generator expression it might be clearer >>> def cube_gen(x): for i in range(x): yield i*i*i >>> list(cube_gen(5)) [0, 1, 8, 27, 64] >>> cube_gen = (i*i*i for i in range(5)) >>> cube_gen <generator object <genexpr> at 0x00ADB060> >>> list(cube_gen) [0, 1, 8, 27, 64]
25th Aug 2018, 3:14 PM
Just A Rather Ridiculously Long Username
+ 1
25th Aug 2018, 6:04 PM
Just A Rather Ridiculously Long Username
0
Thank you for the feedback! I guess my question is the format of the first result though. def my_gen(): n = 1 print('This is printed first') yield n n += 1 print('This is printed second') yield n n += 1 print('This is printed at last') yield n print (list(my_gen())) interesting thing is that it prints out three lines and one line of list for numbers, and that I have no clue :(
25th Aug 2018, 4:26 PM
Vosen Chen
0
@ Just A Rather Ridiculously Long Username, thank you so much! Your explanation really help me clear things up! :)
27th Aug 2018, 5:07 AM
Vosen Chen
0
No problem, cheers :)
7th Sep 2018, 12:16 PM
Just A Rather Ridiculously Long Username
Heute heiß
HELP ME