🐍 A Generator in Python is a function that returns one result at a time for a list. In the example below we will look into a regular function and then we will see a Generator and understand the difference.
YIELD
The following function returns numbers between 0 and any integer you pass to the function:
def call_range(n):
lst1 = []
for x in range(n):
lst1.append(x)
return lst1
#This calls the function in for loop as well as in list form
for y in create_cubes(10):
print(y)
create_cubes(10)
The following function returns numbers between 0 and any integer you pass to the function but one by one as it is generated:
def call_range(n):
for x in range(n):
yield x
for y in create_cubes(10):
print(y)
NEXT()
Next() helps to call the next result as and when we want. Here is an example of how next can be used.
def call_range(n):
for x in range(n):
yield x
y = call_range(10)
next(y)
next(y)
next(y)
ITER()
iter() is used break a string or a list into its elements, that can be then accessed using next(). iter() comes to use when there is no generator with yield:
s = 'hello'
s_iter = iter(s)
next(s_iter)
Comments
Post a Comment