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)))
6 ответов
+ 1
I'm not sure to good understanding your problem...
are you trying to do:
print(list(countdown()))
+ 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
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
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
0
Okz... thanks for help.
- 1
try my code: it works as you expect ;)