Python Practice › Iterator & Generator Programs › Program 3
Countdown generator
Write a generator that counts down from n to 1.
Output
[5, 4, 3, 2, 1]
Approach
yieldinside a while loop.
Solution
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.