Learn about Python Generators

Learn about Python Generators are very easy to implement, but a bit difficult to understand.

Generators are used to create iterators, but with a different approach. Generators are simple functions which return an iterable set of items, one at a time, in a special way.

 

When an iteration over a set of item starts using the for statement, the generator is run. Once the generator’s function code reaches a “yield” statement, the generator yields its execution back to the for loop, returning a new value from the set. The generator function can generate as many values (possibly infinite) as it wants, yielding each one in its turn.

Here is a simple example of a generator function which returns 7 random integers:

import random

def lottery():
    # returns 6 numbers between 1 and 40
    for i in range(6):
        yield random.randint(1, 40)

    # returns a 7th number between 1 and 15
    yield random.randint(1,15)

for random_number in lottery():
       print("And the next number is... %d!" %(random_number))

Trinket.io on-line Python compiler

This function decides how to generate the random numbers on its own, and executes the yield statements one at a time, pausing in between to yield execution back to the main for loop.

Exercise

Write a generator function which returns the Fibonacci series. They are calculated using the following formula: The first two numbers of the series are always equal to 1, and each consecutive number returned is the sum of the last two numbers. Hint: You can use only two variables in the generator function? Remember that assignments can be done simultaneously. The code will simultaneously switch the values of a and b: Try running the code and see for yourself.

a = 1
b = 2
a, b = b, a
print(a,b)

Trinket.io on-line Python compiler

# this is the answer code. see compiler below to create and run your solution.
def fib():
    a, b = 1, 1
    while 1:
        yield a
        a, b = b, a + b

# testing code
import types
if type(fib()) == types.GeneratorType:
    print("Good, The fib function is a generator.")

    counter = 0
    for n in fib():
        print(n)
        counter += 1
        if counter == 10:
            break

Trinket.io on-line Python compiler


Related Videos:

MiltonMarketing.com Related Videos.

Related Posts:

Learn Python Hello World Program

JavaScript Glossary

My little pony learning game in VB.NET

Introduction to JavaScript – CONSOLE

Introduction to JavaScript – Control Flow: if/else Statements

CSS, HTML, JAVASCRIPT, Online Compiler. Code on the go by replit.it

Learn about Python Sets (lists)

Learn Modules and Packages in Python programming

Python Basic String Operations

Learn Code Introspection Python Programming

Learn List Comprehensions in Python Programming

Hello World Android app built with Android Studio

Introduction to JavaScript – Variables: Review

Learn about Python Conditions

Introduction to JavaScript – Control Flow: True and False values

FAQs

Introduction to JavaScript – Variables: String Interpolation

Learn about programming Functions in Python

Introduction to JavaScript – Variables

Who is this Android App Development course for?

What is Python?

Learn Python Lists

Python Basic Operators

Exception Handling in Python programming

Python Basic String Operations

Learn Pandas Basics Python tabular data manipulation

Training needed for thousands of coming computer jobs, says Code NL founder

Python Serialization (JSON)

Learn about Dictionaries datatype for Python

Understanding Floating point number representation

Learn Multiple Function Arguments in Python

Connected through code, Choose Your Platform!

About the Author: Bernard Aybout

In the land of bytes and bits, a father of three sits, With a heart for tech and coding kits, in IT he never quits. At Magna's door, he took his stance, in Canada's wide expanse, At Karmax Heavy Stamping - Cosma's dance, he gave his career a chance. With a passion deep for teaching code, to the young minds he showed, The path where digital seeds are sowed, in critical thinking mode. But alas, not all was bright and fair, at Magna's lair, oh despair, Harassment, intimidation, a chilling air, made the workplace hard to bear. Management's maze and morale's dip, made our hero's spirit flip, In a demoralizing grip, his well-being began to slip. So he bid adieu to Magna's scene, from the division not so serene, Yet in tech, his interest keen, continues to inspire and convene.