(13)GENERATORS:
Generators are functions that produce items one at a time and produce only when asked which can save a lot of memory.
for example:
import sys
def firstn(n):
num, nums = 0, []
while num < n:
nums.append(num)
num += 1
return nums
sum_of_first_n = sum(firstn(1000000))
print(sum_of_first_n)
print(sys.getsizeof(firstn(1000000)), "bytes")
output = 499999500000
8697464 bytes
1.Creating generators:
A generator is defined like a normal function but with yeaild insted of return.
for example:
def my_generator():
yield 1
yield 2
yield 3
2.Executing generators:
Calling a generator does not executes it, because it returns a generators object which is used to control execution.
To execute call the function next().
Comments
Post a Comment
If you have any doubts please let me know