[PYTHON] Generator

in a for loop


l = ['Good morning', 'Hello', 'Good evening']

for i in l:
    print(i)

Execution result in for loop


Good morning
Hello
Good evening

If you write this using a generator,

Generator 1


def greeting():
    yield 'Good morning'
    yield 'Hello'
    yield 'Good evening'

g = greeting()

print(next(g))
print(next(g))
print(next(g))

Execution result of generator 1


Good morning
Hello
Good evening

If you have two generators,

2 generators


def greeting():
    yield 'Good morning'
    yield 'Hello'
    yield 'Good evening'
g = greeting()

def counter(num=10):
    for i in range(num):
        yield 'Gaga Gaga!!!'
c = counter()

print(next(g))

print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))

print(next(g))

print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))

print(next(g))

Execution result of two generators


Good morning
Gaga Gaga!!!
Gaga Gaga!!!
Gaga Gaga!!!
Gaga Gaga!!!
Gaga Gaga!!!
Hello
Gaga Gaga!!!
Gaga Gaga!!!
Gaga Gaga!!!
Gaga Gaga!!!
Gaga Gaga!!!
Good evening

Instead of processing at once like a for loop Keeping the element generation Other processing can be done.

So For example, like the code below If heavy processing is in the middle Rather than doing all the processing at once It can be implemented in small pieces.

Generator heavy


def greeting():
    yield 'Good morning'
    for i in range(1000000):
        print(i)
    yield 'Hello'
    for i in range(1000000):
        print(i)
    yield 'Good evening'

Process yield'Good morning'. for i in range(1000000): You do not have to process print (i).

next for i in range(1000000): print(i) Processing the yield 'Hello'.

It can be processed in small pieces.

Generator error


def greeting():
    yield 'Good morning'
    yield 'Hello'
    yield 'Good evening'

g = greeting()

for i in range(4):
    print(next(g))

Runtime error for generator error


Traceback (most recent call last):
  File "Main.py", line 9, in <module>
    print(next(g))
StopIteration

Good morning, hello, three such to the Good evening, I did 4 prints (next (g)), so StopIteration returns an error.

Recommended Posts

generator
Generator
Generator memo.
Natural number generator
Patterned password generator
Try numpy.random Generator
Hash password generator
[Python] Generator function
Generator function in JavaScript
Generator comprehension notation Tuple comprehension notation
Password generator creation notes
NetworkX graph generator list