New course! Every coder should learn Generative AI!
0

Yield generator

I didn't understand why I can't use list in first yield example ( I tried and got error) but I can do so in second one. First def countdown(): i=5 while i > 0: yield i i -= 1 for i in countdown(): print(i) Second def numbers(x): for i in range(x): if i % 2 == 0: yield i print(list(numbers(11)))

25th May 2021, 8:11 PM
Prabuddh Bhatia
+ 1
I'm not sure to good understanding your problem... are you trying to do: print(list(countdown()))
25th May 2021, 8:20 PM
visph
+ 1
however, you could do simpler to get same result: print(list(range(5,0,-1))) usefulness of generators are revealed by using them for more complex cases ;P
25th May 2021, 8:31 PM
visph
0
The result of first code was 5 4 3 2 1 I wanted to see if I could get it as [5, 4, 3, 2, 1] but faced error
25th May 2021, 8:23 PM
Prabuddh Bhatia
0
visph Thanks... but I still don't get usefulness of yield function. I mean I could have gotten the result of first code by using below instead. i = 5 while i >0: print(i) i = i -1
25th May 2021, 8:29 PM
Prabuddh Bhatia
0
Okz... thanks for help.
25th May 2021, 8:33 PM
Prabuddh Bhatia
- 1
try my code: it works as you expect ;)
25th May 2021, 8:23 PM
visph
Hot today
BOTSS