(Aug-24-2020, 09:42 AM)rama27 Wrote:def output(n): i = n for i in range(0, n-1): return i i +=1 # <-- has no effect because the name i # is assigned by the for-loop # the name i is overwritten with the next value from # the range generator # this is not required arr = [] arr.append(output(10))
The
return
statement return a value and the function is left.Instead, you can convert your function to a
generator
.The keyword
yield
yields something, but does not close the generator context.Your function as a generator:
def output(n): i = n for i in range(0, n-1): yield iCalling the function, returns a generator.
You can iterate over a generator.
my_generator = output(10) my_data = [] for value in my_generator: print(value) my_data.append(value)Or a bit more compact:
my_data = [] for value in output(10): print(value) my_data.append(value)And as a list comprehension:
my_data = [value for value in output(10)]
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!