Hi guys, i'm back! So today we will discuss about generators, which are functions that yield values. The yield keyword is like return, but it doesn't end the function. Here's an example:
def <function_name>(<args>):
# ...
yield <something>
replacing the placeholders:
def sq(x):
for i in range(1, x+1):
yield i ** 2
To call the iterator methods, do this:
for <something> in <method_name>(<args>):
<code>
And here is a full example:
def sq(x):
for i in range(1, x+1):
yield i ** 2
for i in sq(10):
print(i)
"""
1
4
9
16
25
36
49
64
81
100
"""
With that, Goodbye guys! Have a nice day!
Top comments (1)
I corrected the mistake, i meant generators, not iteratiors!