Avoid Nested For Loops with Generators

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

Generators allow you to hook together multiple generators with the yield* syntax. This allows you to branch off into many different types of iterations within the main iteration and covers complex scenarios where you usually end up reaching for nested for loops.

Instructor: [0:00] Now because generators give us iterables and yield* can yield iterables, we can also create a second generator and yield those from another generator. For example, if I call this a shoutIterator, this can be a function, and this can take a word. Then we'll just go ahead and yield the word plus !.

[0:27] Now inside of my reverseIterator, I can yield* my shoutIterator, and we'll just pass in "hello." You'll see hello with an exclamation point. I could shout progressively louder, so 2, 3, and I can get hello and then louder, and louder, or I could combine data from my array, say something like array , then yield out array, array.

[0:55] I could do things like a with one exclamation point, louder and louder, B, and C, all because a generator gives us an iterable which a yield can loop through itself.

[1:07] You're probably thinking if you would do this traditionally you would have done nested for loops or a solution like that. Whereas with generators, you get a very easy-to-follow syntax which is very obvious what it's doing, and rather than nested for loops you're just using a function inside of a function, which is a very common and natural pattern.