Python Practice › Iterator & Generator Programs
Python Iterator & Generator Programs with Solutions
20 iterator and generator programs: iter() and next(), custom iterator classes, generator functions with yield, generator expressions, infinite sequences, pipelines and itertools.
Before you start
Read the Iterators and Generators lesson first if the topic is new to you.
All programs
- #1Use iter() and next()
Write a Python program that walks through a list withiter()andnext().Easy - #2A for loop by hand
Write a Python program that rebuilds aforloop usingwhile,iter()andnext().Easy - #3Countdown generator
Write a generator that counts down from n to 1.Easy - #4Even numbers generator
Write a generator that yields even numbers up to a limit.Easy - #5Fibonacci generator
Write a generator that yields Fibonacci numbers, and take the first 10.Easy - #6Generator expression of squares
Write a Python program that sums squares with a generator expression.Easy - #7Custom iterator class
Write an iterator class that returns the characters of a word in reverse.Medium - #8Iterable class with a generator method
Write a class whose objects can be looped over many times.Easy - #9Read a file lazily
Write a generator that yields non-empty, stripped lines from a file.Easy - #10Generator pipeline
Write a pipeline of generators that reads numbers, keeps the even ones and squares them.Medium - #11Split a list into chunks
Write a generator that yields chunks of a given size.Easy - #12Flatten nested lists with yield from
Write a recursive generator that flattens nested lists.Medium - #13Running total
Write a generator that yields the running total of a list.Easy - #14Unique id generator
Write a generator that produces ids like TC-001, TC-002, …Easy - #15Cycle through values
Write a Python program that assigns browsers to 7 tests in rotation.Easy - #16Iterators from zip and enumerate
Write a Python program that shows zip and enumerate return iterators.Easy - #17Generator vs list memory
Write a Python program that compares the memory of a list and a generator of a million numbers.Easy - #18Send values into a generator
Write a generator that keeps a running average of values sent to it.Medium - #19Take values while a condition holds
Write a Python program that takes Fibonacci numbers while they are below 100.Easy - #20Group consecutive items
Write a Python program that groups log lines by level withitertools.groupby.Easy