Even numbers generator

EasyIterator & Generator Programs · 4 of 20

Write a generator that yields even numbers up to a limit.

Advertisement
Output
[0, 2, 4, 6, 8, 10, 12]

Approach

  1. Loop with a step of 2 and yield each value.

Solution

Python
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.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Leave a Comment