Python Generators

1) Simple Generator Function

Write a generator function count_up_to(n) that yields numbers from 1 to n. Test it with n = 5.


2) Generator for Even Numbers

Write a generator that yields even numbers from 2 up to 20.


3) Use next()

Call the generator from #1 and get values using next() until it ends.


4) Catch Generator End

Use try/except StopIteration while calling next() to safely stop.


5) Loop Through Generator

Use a for loop to print values from a generator that yields 1,2,…,10.


6) Generator for Squares

Write a generator that yields squares of numbers from 1 to 10.


7) Generator Expression (List)

Use a generator expression to yield cube values for numbers 1–5, then convert to a list.


8) Yield Characters of a String

Write a generator that yields each character of a user-entered string.


9) Even Filter Generator

From a list [1,2,3,…,10], use a generator expression to yield only even numbers.


10) Infinite Generator (but stop at 10)

Write a generator that yields integers starting from 1 indefinitely. Use a loop to print first 10 values.


11) Generator for Fibonacci

Write a generator that yields Fibonacci sequence numbers up to n terms.


12) Yield Word Lengths

Given list ["cat","dog","lion"], write a generator to yield each word’s length.


13) Prime Number Generator

Write a basic generator that yields prime numbers up to 50.


14) Generator to Read File

Write a generator that reads a text file line by line (yield each line). Test with a small sample file.


15) Combined Generator Expression

Create nested generator expression that yields all products i * j for i in [1,2] and j in [3,4].

Expected output:


16) Filter & Transform

Given list [1,2,3,4,5,6], use generator expression to yield squares only of odd numbers.


17) Delay Execution Demo

Create a generator that prints a message before yielding each number — show it prints only when you iterate.


18) Generator with yield from

Make a generator that yields values from two other generators using yield from.


19) Generator for Alphabet

Write a generator that yields letters a to z (use string.ascii_lowercase or ord/chr logic).


20) Custom Step Generator

Write a generator function step_generator(start, step, limit) yielding values:

Test with start=2, step=3, limit=20.


🧠 Concepts Practiced

Topic
Example

yield keyword

Creating generator functions

Generator expressions

[x*2 for x in …] but as (x*2 for x in …)

next()

Manual iteration

StopIteration

End of generator

yield from

Delegating to another iterator

Infinite/finite iteration

Controlled loops


📌 Starter Snippet

Basic generator

Generator expression


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated