Header Ads

Responsive Ads Here

Generators in Python

generator in Python


l = [1,2,3,4,5]
# list ----> whole list will get added to memory(occupies more space)
# generator ----> (1) ---replace---> (2)


def my_func(n):
    for i in range(1,n+1):
        yield(i)

num = my_func(10)

for i in num:
    print(i)

for i in num:
    print(i)


sq = (i ** 2 for i in range(1,11))
print(sq)

for i in sq:
    print(i)

for i in sq:
    print(i)

Powered by Blogger.