DEV Community

RocketMaker69
RocketMaker69

Posted on • Edited on

Generators in Python

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>
Enter fullscreen mode Exit fullscreen mode

replacing the placeholders:

def sq(x):
    for i in range(1, x+1):
        yield i ** 2
Enter fullscreen mode Exit fullscreen mode

To call the iterator methods, do this:

for <something> in <method_name>(<args>):
    <code>
Enter fullscreen mode Exit fullscreen mode

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
"""
Enter fullscreen mode Exit fullscreen mode

With that, Goodbye guys! Have a nice day!

Top comments (1)

Collapse
 
rocketmaker69 profile image
RocketMaker69

I corrected the mistake, i meant generators, not iteratiors!