Python Practice › Iterator & Generator Programs › Program 4
Even numbers generator
Write a generator that yields even numbers up to a limit.
Output
[0, 2, 4, 6, 8, 10, 12]
Approach
- Loop with a step of 2 and yield each value.
Solution
def evens(limit): for n in range(0, limit + 1, 2): yield n print(list(evens(12)))Output
[0, 2, 4, 6, 8, 10, 12]
Learn the concept
New to this topic? Read the lesson, then come back.