Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Chained Generators | Advanced Generator Patterns and Applications
Efficient Data Handling in Python

bookChallenge: Chained Generators

In this task, you will deepen your understanding of generator delegation and chaining by implementing two separate generator functions: one that yields a sequence of numbers and another that yields the squares of those numbers. You will then use the yield from statement to chain these generators, producing a single combined sequence that first yields all numbers and then their squares. This exercise builds on your knowledge of generator functions and the use of yield from for delegation, as introduced in the previous chapter.

Task

Swipe to start coding

Implement two generator functions: number_generator, which yields numbers from 1 to n, and square_generator, which yields the squares of numbers from 1 to n. Then, implement chained_generator that uses yield from to yield all values from number_generator(n) followed by all values from square_generator(n). The combined sequence should first yield all the numbers, then all their squares.

Solution

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 3
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

close

bookChallenge: Chained Generators

Swipe to show menu

In this task, you will deepen your understanding of generator delegation and chaining by implementing two separate generator functions: one that yields a sequence of numbers and another that yields the squares of those numbers. You will then use the yield from statement to chain these generators, producing a single combined sequence that first yields all numbers and then their squares. This exercise builds on your knowledge of generator functions and the use of yield from for delegation, as introduced in the previous chapter.

Task

Swipe to start coding

Implement two generator functions: number_generator, which yields numbers from 1 to n, and square_generator, which yields the squares of numbers from 1 to n. Then, implement chained_generator that uses yield from to yield all values from number_generator(n) followed by all values from square_generator(n). The combined sequence should first yield all the numbers, then all their squares.

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 3
single

single

some-alt