PRACTICE

Generators

Lesson notes

Your task

Write a generator evens(limit) that yields even numbers from 2 up to limit. Print list(evens(10)).

Expected output
[2, 4, 6, 8, 10]
Loading…

OUTPUT

Worked solution
def evens(limit):
    n = 2
    while n <= limit:
        yield n
        n += 2

print(list(evens(10)))

Checks compare printed output, not your approach. Several solutions can be valid.

← Back to courses