Generators in Python✌
GENERATORS
A generator expression yields a new generator object. Its syntax is the same as for comprehensions, except that it is enclosed in parentheses instead of brackets or curly braces.
Generator Expression is written within
The generator is a function that returns an object (iterator) which we can iterate over (one value at a time). The performance improvement from the use of generators is the result of the lazy (on-demand) generation of values, which translates to lower memory usage.
Generator Expression is written within
()
.It yields a generator. The generator is a function that returns an object (iterator) which we can iterate over (one value at a time). The performance improvement from the use of generators is the result of the lazy (on-demand) generation of values, which translates to lower memory usage.
Return Type: Generator object
![]() |
Generators |
Example for generators:
g=(n for n in range(1,11) if n%2==0)
print (g)
#Output: <generator object <genexpr> at 0x0116C728>
#We can loop through generator object.
for i in g:
print (i, end=" ")
#Output: 2 4 6 8 10
#We can convert generator object into a list.
l=list(g)
print (l)
#Output: [2, 4, 6, 8, 10]
next() : This method is used to extract values one by one when the method is called.
g=(n for n in range(1,11) if n%2==0)
next(g)# 2
next(g)# 4
next(g)# 6
next(g)# 8
next(g)# 10
next(g)# StopIteration
Comments
Post a Comment