
Title:
0356 Generators

Description:

These list comprehensions are amazing.

They are one of my favorite parts of Python.

This is really a great way to program. It's very declarative.

You just say what you want, and the system makes it for you.

Unfortunately, they have a slight downside, which is that thus far

we've had to write out the starter list, and that's almost as much work

as just writing down what we need.

If only there were some way to generate this list,

especially if it's really big, without us having to write it down explicitly.

For example, suppose I started with a big list like this, 1, 2, 3, 4, 5, 6, 7.

I assert it's big. It's big for me.

This is heavy lifting for your professor.

And what I want to do is filter it down so that we only have the odd numbers.

I want to get this part out.

I'm going to show you a new way to do that in Python.

Here I've written a procedure called odds_only in Python

that takes a list of numbers, and it's going to iterate over them.

For every n in that list of numbers, if that number is odd,

we divide it by 2 and check the remainder.

5 divided by 2 is 4 with remainder 1, so it's odd.

We yield that part into our results.

Note that I did not write the word "return."

Yield is a new special keyword that means we can use this sort of procedure

to gather up multiple results.

Let's imagine that this big list here was numbers.

We'll yield 1, not do anything with 2, yield 3,

not do anything with 4, yield 5, not do anything with 6, and yield 7,

and that's exactly the output that we wanted.

You can view this as sort of a convenient way of filtering.

Here I've written out our odds_only procedure.

I'm just going to show you in the interpreter how this plays out.

I'm using a list comprehension.

I want to print out every value of x that's in odds_only of 1, 2, 3, 4, 5,

and we get 1, 3, and 5, as we expected.

I'm also going to show you an even easier way to do this.

Snap, it'll be so cool.

Here I've written a list comprehension.

I want [x for x in [1, 2, 3, 4, 5].

But over here on the right I've put this sort of if conditional,

a guard or a predicate we might call it in mathematics,

and this is saying I only want you to yield

those numbers for which the predicate is true.

Only include x in the answer if x was an odd number,

and look, we get the answer we wanted.

I've written x a few times, but I can make these formulas

arbitrarily more complicated.

Here I've said take all of the odd numbers, and multiply them by 2.

Since 1, 3, and 5 were the odd numbers, 2, 6, and 10 are the multiplication by 2.

I love list comprehensions, and you will too soon.

A function like odds_only that uses yield

to potentially return multiple answers is called a generator

because you can use it to generate another list or another enumeration.