Skip to content
Home » Generators Passed as Arguments

Generators Passed as Arguments

Spread the love

Today we’ll be talking about passing generators as arguments to other generators.

If you haven’t read my previous five articles on generators (basics of generators, sending objects to generators, the throw method, the yield from statement and recursive generators), I definitely recommend to do so before you go on with this one.  

generators as arguments

We can pass strings, lists, numbers, etc. as arguments to generators. We can also pass other generators. Let’s define an infinite generator of arithmetic sequences.

Arithmetic Sequence Recap

An arithmetic sequence is a sequence of numbers such that the distance between the consecutive elements (which we call terms) is constant. In order to define an arithmetic sequence we need two things: the first term and the difference between consecutive terms, called the common difference.

Suppose we have an arithmetic sequence with the first term 2 and the common difference 3, so the first terms of the sequence are: 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, … As we can see, the first term is 2 and then each following term is 3 more than the previous one.

Arithmetic Sequence Generator

Now we’ll code a generator that, given the first term and the common difference, will generate an infinite arithmetic sequence.

def arithmetic_sequence(term1, common_difference):
    term = term1    
    while True:
        yield term
        term += common_difference

But infinite sequences are not what we always want. That’s why we’ll create another generator that will limit the number of terms that will be returned:

def limiter(it, limit):
    for n in range(limit):
        yield next(it)

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

The limiter generator will take the arithmetic_sequence generator and the limit as arguments and produce the first terms – as many as the limit is set to – of the arithmetic sequence. Here’s the code:

print(list(limiter(arithmetic_sequence(2, 3), 20)))

And here’s the output if the limit is set to 20 terms:

[2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53, 56, 59]

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of the article:


Spread the love

Leave a Reply