Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Using Advanced Generator Methods

In this lesson, you’ll learn about the advanced generators methods of .send(), .throw(), and .close(). To practice with these new methods, you’re going to build a program that can make use of each of the three methods.

As you follow along in the lesson, you’ll learn that yield is an expression, rather than a statement. You can use it as a statement, but you can manipulate a yielded value. You are allowed to .send() a new value back to the generator. You’ll also handle exceptions with .throw() and stop the generator after a given amount of digits with .close().

Comments & Discussion

zell0ss on June 17, 2020

Great tutorial,

A curiosity I seem unable to answer, why the palindromes found are:

11 111 1111 10101

instead

11 101 1001 10001

At first I thought that was because we send 10 (digits) and it got incremented just afterwards so it will skip 101, 1001, … I changed it to 10 (digits) -1 but got the same result.

I know it is not strictly generator related, but nonetheless, Im curious!

zell0ss on June 17, 2020

Ahhh! forgot markdown: i mean we send 10 ** (digits) and I changed to 10 ** (digits) -1

Pierre on June 19, 2020

Goodness, that was wonderfully clear. It’s the first time I’ve been able to follow a presentation of generators. Thanks, Christian.

My only regret is you didn’t walk through the calling of a generator comprehension as you did a generator function in video 2. I’ll do so myself expecting they are called in the same manner.

Thanks, again

Howard M Sherman on June 28, 2020

Something doesn’t make sense to me in the sequence of palindromes being printed. Using your .throw() method sample, the output is:

11 111 1111 10101 Traceback (most recent call last): . . ValueError: We don’t like large palindromes

Following the logic of your code, I would think the sequence of palindromes printed would be: 11 101 1001 10001

Since the for loop is running “pal_gen.send(10 (digits))”, it would seem to me first palindrome following each “10 (digits)” sent would be that number + 1. Am I missing something?

Eron on June 29, 2020

It’s nice, but I have a question: why don’t we raise an exception directly in test code or in the infinite_palindrome method instead using throw() method?

Become a Member to join the conversation.