Countdown generator

EasyIterator & Generator Programs · 3 of 20

Write a generator that counts down from n to 1.

Advertisement
Output
[5, 4, 3, 2, 1]

Approach

  1. yield inside a while loop.

Solution

Python
def countdown(n):    while n > 0:        yield n        n -= 1 print(list(countdown(5)))
Output
[5, 4, 3, 2, 1]

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